在 Spring Web 应用程序中,会话(Session)超时是指用户在一段时间内没有与服务器交互后,服务器自动终止该用户的会话状态。当应用程序使用 Ajax 轮询(定期向服务器发送请求)时,可能会遇到会话超时的特殊问题。
在 application.properties
或 application.yml
中:
# 设置会话超时时间为1小时(以秒为单位)
server.servlet.session.timeout=3600
@RestController
public class SessionController {
@GetMapping("/keep-alive")
public ResponseEntity<?> keepAlive(HttpSession session) {
// 触摸会话以重置超时计时器
session.setAttribute("lastAccess", System.currentTimeMillis());
return ResponseEntity.ok().build();
}
}
// 定期发送保持会话的请求
setInterval(() => {
fetch('/keep-alive')
.then(response => {
if (!response.ok) {
// 处理会话超时
window.location.href = '/login?timeout=true';
}
})
.catch(error => console.error('Keep-alive failed:', error));
}, 5 * 60 * 1000); // 每5分钟一次
@Configuration
public class SessionConfig implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
se.getSession().setMaxInactiveInterval(3600); // 1小时
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
// 会话销毁时的处理
}
}
@ControllerAdvice
public class SessionTimeoutHandler {
@ExceptionHandler(SessionExpiredException.class)
@ResponseBody
public ResponseEntity<?> handleSessionExpired() {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(Collections.singletonMap("error", "session_expired"));
}
}
通过以上方法,可以有效解决 Spring Web 应用中 Ajax 轮询导致的会话超时问题,提供更好的用户体验。