Java Spring中会话过期的监听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19534502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Listener for Session Expiration in Spring
提问by Prashant
I am new to spring security and using it for authentication. I am facing a issue that when the browser is closed or in case of any unusual failure the session expires but I am unable catch the event so as to get the clean up code executed.
I explore about it and found HttpSessionEventPublisher
in Spring to capture HttpSessionDestroyedEvent
in sessionDestroyed()
method but that is not called when I close the browser.
我是 Spring Security 的新手并使用它进行身份验证。我面临的问题是,当浏览器关闭或出现任何异常故障时,会话会过期,但我无法捕获该事件以执行清理代码。我探索了它,并HttpSessionEventPublisher
在 Spring 中找到了HttpSessionDestroyedEvent
在sessionDestroyed()
方法中捕获但在我关闭浏览器时不会调用的方法。
Request to suggest solution for the same.
请求建议相同的解决方案。
回答by Ernestas Kardzys
Maybe SessionManagementFiltercould help?
也许SessionManagementFilter可以提供帮助?
Or you can configure Spring Security to automatically redirect user if timeout occured: Detecting timeoutssection.
回答by Ralph
You need to register the listener in the web.xml
!
您需要在web.xml
!
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
But of course it detect only that the session is closed (because of an timeout or some explicite programmatic session destroy), but it does not detect that someone close his browser. This is because there is no http notification about a closed brwoser.
但是当然它只检测到会话已关闭(由于超时或某些明确的程序化会话破坏),但它不会检测到有人关闭了他的浏览器。这是因为没有关于关闭的浏览器的 http 通知。
回答by Human Being
You can use the JQueryto solve the browser closing problem ,
可以使用JQuery解决浏览器关闭问题,
The JQuerywill be ,
在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);
}
});
});
In Spring controller,
在弹簧控制器中,
@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();
}
In web.xmladd this , If you used HttpSessionEventPublisher to catch the session destroy event,
在web.xml添加这个,如果你使用 HttpSessionEventPublisher 来捕捉会话销毁事件,
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
Hope this helps.
希望这可以帮助。