springmvc sessionfilter 登陸過濾器

1.在web.xml中配置java

 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類web

 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 }
View Code

 3.歡迎你們➕我微信一塊兒探討,微信號:kj19960106spring

相關文章
相關標籤/搜索