我有一个单页应用程序,使用Jquery编写,后端使用java。
session 超时后,如果用户执行某些触发 Ajax 调用的 Activity ,则应将用户重定向到登录屏幕。
如果它是另一个页面请求,那么以下解决方案可能有效,但由于它是 Ajax 调用,重定向只是对成功函数给出另一个响应。
我试过了
在主过滤器中
HttpSession session = request.getSession(false); if(session != null && !session.isNew()) { chain.doFilter(request, response); }else { response.sendRedirect("/login.jsp"); }
通过在 ajax 调用中从主过滤器内部发送以下 header 来刷新选项卡
httpResponse.setHeader("Refresh", "0; URL=" + targetUrl);
最佳答案
服务器端:添加一个过滤器,它将针对每个请求进行处理,在该过滤器的 doFilter 方法中添加以下代码:
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = httpRequest.getSession(false);// don't create if it doesn't exist
if(session == null || session.isNew()) {
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // status code is 401
}else{
// pass the request along the filter chain
chain.doFilter(request, response);
}
客户端:配置 ajax,使其在收到状态代码为 401 的任何响应时重新加载选项卡或更改 window.location。这是如何使用 jquery 完成的:
$(window).load(function(){
$.ajaxSetup({
statusCode: {
401: function(){
location.reload(); // or window.location="http://www.example.com"
}
}
});
});
对我来说重新加载就足够了,让用户进入登录屏幕
关于java - 如何将用户重定向到登录屏幕,如果在 session 超时后收到 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46357022/