Java后台判断ajax请求 Java后台判断ajax请求及处理过程详解
风缱云流 人气:0一、问题描述:
当访问一个需要登录的页面时,会有过滤器或者拦截器进行过滤拦截,如果用户没有登录,则跳转到登录页面。
当用户已经登录进入系统后,然后长时间没操作,等到session过期后,再点击一个ajax请求操作时,这时再跳转到登录页面就不合适了,因为这是ajax操作,拦截后跳到页面返回的结果js识别不了。
二、解决方法:
在过滤器或者拦截器上做识别,针对页面跳转请求和ajax请求分别处理。
页面跳转的不再详说,现在说的是ajax请求。
直接贴代码:
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component("authenticationFilter") public class AuthenticationFilter implements Filter { @Autowired SessionContext sessionContext; private Logger log = LoggerFactory.getLogger(AuthenticationFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse res = (HttpServletResponse) response; //判断是否为ajax请求,默认不是 boolean isAjaxRequest = false; if(!StrUtils.isBlank(req.getHeader("x-requested-with")) && req.getHeader("x-requested-with").equals("XMLHttpRequest")){ isAjaxRequest = true; } SysUser sysUser = sessionContext.getSysUserFromSession(req); if (sysUser != null && sysUser.getUserId() != null) { chain.doFilter(req, res); }else{//Session用户为空,登录过期 if(isAjaxRequest){// 如果是ajax请求,则不是跳转页面,使用response返回结果 res.setHeader("noAuthentication", "true"); ResultWithObject resultWithObject = new ResultWithObject(CC.NEGATIVE_1, CC.RESULT_MESSAGE_TEXT_DEFAULT); resultWithObject.setMsg("登录已失效,请刷新页面或重新登录!"); res.setContentType("application/json;charset=UTF-8"); PrintWriter writer = res.getWriter(); writer.write(JasonUtils.Object2String(resultWithObject)); writer.close(); res.flushBuffer(); }else{ res.sendRedirect("http://xxxx.com/loginUI"); } } } @Override public void destroy() { } }
加载全部内容