Spring中会话过期的监听器

我是Spring的新手,并将其用于身份validation。 我遇到一个问题,当浏览器关闭或者在任何exception失败的情况下会话到期但我无法捕获事件以便执行清理代码。 我探索它并在Spring中发现HttpSessionEventPublishersessionDestroyed()方法中捕获HttpSessionDestroyedEvent ,但是当我关闭浏览器时不会调用它。

请求建议相同的解决方案。

也许SessionManagementFilter可以提供帮助?

或者,您可以将Spring Security配置为在发生超时时自动重定向用户: 检测超时部分。

您需要在web.xml注册监听器!

    org.springframework.security.web.session.HttpSessionEventPublisher   

但当然它只检测会话被关闭(因为超时或某些明确的程序会话销毁),但它没有检测到有人关闭了他的浏览器 。 这是因为没有关于关闭的brwoser的http通知。

您可以使用JQuery来解决浏览器关闭问题,

JQuery将是,

 $(window).on('beforeunload', function(){ return 'Are you sure you want to leave?'; }); $(window).on('unload', function(){ //alert("unload"); $.ajax({ type: "POST", url: "Logout.html", //data: "message=" + message, dataType: "html", success: function(response) { }, error: function(e) { //alert('Error: ' + e); } }); }); 

Spring控制器中

 @RequestMapping(value="Logout.html",method=RequestMethod.POST) public @ResponseBody String logout(HttpSession session){ System.out.println("Request Logout"); // Do you work before invalidate the session session.invalidate(); } 

web.xml中添加此项,如果您使用HttpSessionEventPublisher来捕获会话销毁事件,

    org.springframework.security.web.session.HttpSessionEventPublisher   

希望这可以帮助。