Java過濾器處理Ajax請求,Java攔截器處理Ajax請求,攔截器Ajax請求java
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>ajax
©Copyright 蕃薯耀 2017年8月10日spring
http://www.cnblogs.com/fanshuyao/json
1、問題描述:session
當訪問一個須要登陸的頁面時,會有過濾器或者攔截器進行過濾攔截,若是用戶沒有登陸,則跳轉到登陸頁面。app
當用戶已經登陸進入系統後,而後長時間沒操做,等到session過時後,再點擊一個ajax請求操做時,這時再跳轉到登陸頁面就不合適了,由於這是ajax操做,攔截後跳到頁面返回的結果js識別不了。ide
2、解決方法:spa
在過濾器或者攔截器上作識別,針對頁面跳轉請求和ajax請求分別處理。blog
頁面跳轉的再也不詳說,如今說的是ajax請求。get
直接貼代碼:
- 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() {
- }
- }
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
©Copyright 蕃薯耀 2017年8月10日
http://www.cnblogs.com/fanshuyao/