1.问题描述:
最近自己在写demo时遇到一个问题,在ajax请求时用Filter做登录拦截,结果页面不跳转(Ajax是不能做转发和重定向的)、、、、
最终的最终在同事zt的提示下,恍然大悟,虽然很基本的问题,但也纠结了好久,只能说太菜,记录下来,以免以后再犯。
2.解决办法:
在doFilter方法中判断是否为Ajax请求,做进一步处理
代码如下:
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
HttpServletResponse resp=(HttpServletResponse) response;
HttpServletRequest req=(HttpServletRequest) request;
String url = req.getRequestURI();
System.out.println(url);
HttpSession session = ((HttpServletRequest) request).getSession();
String path = req.getContextPath();
String basePath= req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path+"/";
basePath=basePath+"rest/userManager/loginOut";
try {
// 过滤掉登陆和退出请求
if ((url.indexOf("/ddoa/rest/userManager/login") >= 0)|| (url.indexOf("/ddoa/rest/userManager/loginOut") >= 0)) {
chain.doFilter(request, response);
} else {
if (null != session) {
Map<Object, Object> map = (Map<Object, Object>) session.getAttribute("userMap");
if(null!=map){
chain.doFilter(request, response);
}else{
//1:判断是否是ajax请求
if (req.getHeader("x-requested-with") != null&& "XMLHttpRequest".equalsIgnoreCase(req.getHeader("x-requested-with"))) {
//向http头添加 状态 sessionstatus
resp.setHeader("sessionstatus","timeout");
resp.setStatus(403);
//向http头添加登录的url
resp.addHeader("loginPath", basePath);
chain.doFilter(request, response);
return ;
}else{
resp.sendRedirect(basePath);
}
}
} else {
//1:判断是否是ajax请求
if (req.getHeader("x-requested-with") != null&& "XMLHttpRequest".equalsIgnoreCase(req.getHeader("x-requested-with"))) {
//向http头添加 状态 sessionstatus
resp.setHeader("sessionstatus","timeout");
resp.setStatus(403);
//向http头添加登录的url
resp.addHeader("loginPath", basePath);
chain.doFilter(request, response);
return ;
}else{
resp.sendRedirect(basePath);
}
}
}
} catch (IOException | ServletException e) {
e.printStackTrace();
}
}