springmvc sessionfilter 登录过滤器
1.在web.xml中配置
1 <!-- sessionfilter --> 2 3 <filter> 4 <filter-name>sessionFilter</filter-name> 5 <filter-class>com.juin.filter.SessionFilter</filter-class> 6 </filter> 7 8 <filter-mapping> 9 <filter-name>sessionFilter</filter-name> 10 <url-pattern>/*</url-pattern> 11 </filter-mapping> 12 13 <!--以上截止sessionfilter -->
2.创建SessionFilter类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.juin.filter; 2 3 import java.io.IOException; 4 import javax.servlet.FilterChain; 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 import org.springframework.http.HttpStatus; 10 import org.springframework.web.filter.OncePerRequestFilter; 11 12 public class SessionFilter extends OncePerRequestFilter { 13 @Override 14 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 15 throws ServletException, IOException { 16 17 // 不过滤的uri 18 String[] notFilter = new String[] { "/user/toUser", "/login", "user/toMain" }; 19 20 // 请求的uri 21 String uri = request.getRequestURI(); 22 // 是否过滤 23 boolean doFilter = true; 24 for (String s : notFilter) { 25 if (uri.indexOf(s) != -1) { 26 // 如果uri中包含不过滤的uri,则不进行过滤 27 doFilter = false; 28 break; 29 } 30 } 31 32 if (doFilter) { 33 // 执行过滤 34 // 从session中获取登录者实体 35 Object obj = request.getSession().getAttribute("temp_user"); 36 if (null == obj) { 37 boolean isAjaxRequest = isAjaxRequest(request); 38 if (isAjaxRequest) { 39 response.setCharacterEncoding("UTF-8"); 40 response.sendError(HttpStatus.UNAUTHORIZED.value(), "您已经太长时间没有操作,请刷新页面"); 41 return; 42 } 43 response.sendRedirect("../user/toUser"); 44 return; 45 } else { 46 // 如果session中存在登录者实体,则继续 47 filterChain.doFilter(request, response); 48 } 49 } else { 50 // 如果不执行过滤,则继续 51 filterChain.doFilter(request, response); 52 } 53 } 54 55 /** 56 * 判断是否为Ajax请求 <功能详细描述> 57 * 58 * @param request 59 * @return 是true, 否false 60 * @see [类、类#方法、类#成员] 61 */ 62 public static boolean isAjaxRequest(HttpServletRequest request) { 63 String header = request.getHeader("X-Requested-With"); 64 if (header != null && "XMLHttpRequest".equals(header)) 65 return true; 66 else 67 return false; 68 } 69 }
3.欢迎大家➕我微信一起探讨,微信号:kj19960106