在 Spring MVC 中检测 Ajax 请求中的会话超时
我似乎找不到关于如何在会话超时时从 ajax 请求发回一些数据的好示例/答案。它发送回登录页面 HTML,我想发送 json 或我可以拦截的状态代码。
I can't see seem to find a good example/answer on how to send back some data from an ajax request when a session has timed out. It sends back the login page HTML and I want to either send json or a status code I can intercept.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最简单的方法是对 AJAX 请求的 URL 使用过滤器。
在下面的示例中,我只是发送 HTTP 500 响应代码,并带有指示会话超时的响应正文,但您可以轻松地将响应代码和正文设置为更适合您的情况。
The simplest way for doing this is using a filter on URLs of your AJAX requests.
In the example below I'm just sending HTTP 500 response code with a response body indicating the session timeout, but you can easily set the response code and body to what is more suitable for your case..
这是我认为非常简单的方法。这是我在该网站上观察到的方法的组合。我写了一篇关于它的博客文章:
http://yoyar. com/blog/2012/06/dealing-with-the-spring-security-ajax-session-timeout-problem/
基本思想是使用上面建议的 api url 前缀(即 /api/secured)以及身份验证入口点。它简单且有效。
这是身份验证入口点:
这是 spring 上下文 xml 中的内容:
Here's an approach that I think is quite simple. It's a combination of approaches that I've observed on this site. I wrote a blog post about it:
http://yoyar.com/blog/2012/06/dealing-with-the-spring-security-ajax-session-timeout-problem/
The basic idea is to use an api url prefix (i.e. /api/secured) as suggested above along with an authentication entry point. It's simple and works.
Here's the authentication entry point:
And here's what goes in your spring context xml:
我在后端使用@Matt 的相同解决方案。如果您在前端使用 AngularJs,请在 Angular $http 中添加以下拦截器,让浏览器实际重定向到登录页面。
});
请注意,仅当您在 1.1.1 版本之后使用 AngularJs 时才需要下面的行(AngularJS 从该版本开始删除了标头“X-Requested-With”)
I use the same solution by @Matt in backend. If you're using angularJs on front end, add below interceptor in angular $http to let browser actually do a redirect to login page.
});
Note that below line is needed only if you're using AngularJs after version 1.1.1 (angularJS removed header "X-Requested-With" from that version onward)
鉴于目前所有的答案都已经有几年了,我将分享我目前在 Spring Boot REST 应用程序中工作的解决方案:
这里的基本前提是我覆盖默认情况下发出的身份验证入口点重定向到我不存在的登录页面。现在,它通过发送 401 进行响应。Spring 还隐式创建一个它也返回的标准错误响应 JSON 对象。
Seeing as all of the present answers are a few years old now, I'll share my solution which I currently have working in a Spring Boot REST application:
The basic premise here is that I override the authentication entry point which by default was issuing a redirect to my non-existent login page. It now responds by sending a 401. Spring also implicitly creates an standard error response JSON object that it returns as well.