session expired, intercept ajax request and jump to login page

Keywords: Java JSP Session JSON

1. Method 1: 1.1 use filter and ajax setup to intercept ajax and jump to the login page

 1 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
 2             throws IOException, ServletException {
 3 
 4         HttpServletResponse hresponse = (HttpServletResponse)response;
 5         HttpServletRequest hrequest = (HttpServletRequest)request;
 6         HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response);
 7 
 8         String logonStrings = config.getInitParameter("logonStrings");        // Login page
 9         String redirectPath = hrequest.getContextPath() + config.getInitParameter("redirectPath");// No landing page
10         String disabletestfilter = config.getInitParameter("disabletestfilter");// Whether the filter is effective
11         String reString = hrequest.getRequestURI();
12         if (disabletestfilter.toUpperCase().equals("Y")) {    // Filtering invalid
13             chain.doFilter(request, response);
14             return;
15         }
16 //        User user = ( User ) hrequest.getSession().getAttribute("user");//Determine whether the user is logged in
17         String session_key = (String) hrequest.getSession().getAttribute("token");
18         String username = (String) hrequest.getSession().getAttribute("username");
19         if ("".equals(session_key) || session_key == null) {
20             String[] logonList = logonStrings.split(",");
21             if (this.isContains(reString, logonList)) {// Do not filter login page
22                 chain.doFilter(request, response);
23                 return;
24             }else{
25                 request.setAttribute("username", null);
26                 boolean isAjaxRequest = this.isAjaxRequest(hrequest);
27                 if (isAjaxRequest) {
28                     //Root of system url
29                     chain.doFilter(request, response);
30                     return;
31                 }
32                 wrapper.sendRedirect(redirectPath);
33                 return;
34             }
35         }else {
36             if(username !=null || username .equals("")) {
37                 Pattern pattern = Pattern.compile("/iad/");
38                 Matcher matcher = pattern.matcher(reString);
39                 Pattern pattern1 = Pattern.compile("/iad/views/login/login.jsp");
40                 Matcher matcher1 = pattern1.matcher(reString);
41                 if(matcher.matches() ||matcher1.matches()){
42                     wrapper.sendRedirect("/iad/views/home/index.jsp");
43                     return;
44                 }else {
45                     chain.doFilter(request, response);
46                     return;
47                 }
48             }else{
49                 boolean isAjaxRequest = this.isAjaxRequest(hrequest);
50                 if (isAjaxRequest) {
51                     chain.doFilter(request, response);
52                     return;
53                 }
54                 Pattern pattern = Pattern.compile(".*\\/views\\/login\\/login\\.jsp");
55                 Matcher matcher = pattern.matcher(reString);
56                 Pattern pattern2 = Pattern.compile(".*\\/oms/");
57                 Matcher matcher2 = pattern2.matcher(reString);
58                 // Is it the landing page
59                 if (matcher.matches() || matcher2.matches()) {
60                     request.setAttribute("username", username);
61                     wrapper.sendRedirect("/iad/views/home/index.jsp");
62                     return;
63                 }
64                 chain.doFilter(request, response);
65                 return;
66             }
67 
68         }
69 
70     }

Judge whether it is ajax

1  public static boolean isAjaxRequest(HttpServletRequest request) {
2         String header = request.getHeader("X-Requested-With");
3         if (header != null && "XMLHttpRequest".equals(header))
4             return true;
5         else
6             return false;
7     }

1.2 global js code can extract public js and introduce it to the page you want

 1 $.ajaxSetup( {
 2         type: "POST" , // Default use POST mode
 3         headers: { // Add request header by default
 4             "Author": "CodePlayer" ,
 5             "Powered-By": "CodePlayer"
 6         } ,
 7         error: function(xhr, textStatus, errorMsg){ // Default handler on error
 8           var sessionStatus = xhr.getResponseHeader('sessionstatus');
 9         if(sessionStatus == 'timeout') {
10             var top = getTopWinow();
11             var ids=layer.alert("Import succeeded!");
12             window.location.href = "/iad/veiws/login/login.jsp";
13         }
14 
15         }
16     } );

Conclusion: there is a problem with this method, that is, the error method in ajax must go, and the reminder message will appear twice

Method 2: use js timer to query the foreground session (if you want to put this JS on the public page)

 1  @ResponseBody
 2     @RequestMapping("/loginCheck")
 3     public Boolean loginCheck(HttpServletRequest request, HttpServletResponse response) {
 4 
 5         String session_key = (String) request.getSession().getAttribute("token");
 6         String username = (String) request.getSession().getAttribute("username");
 7         if (session_key == null || username == null) {
 8             response.setHeader("sessionstatus", "timeout");
 9             return false;
10         }
11         return true;
12     }
 var timeid=window.setInterval("checkSession()", 1000);
             checkSession= function () {
                 $.ajax({
                     url: "../../loginCheck",
                     type: "POST",
                     dataType: "json",
                     success: function (result) {
                         if (result != true) {
                             window.clearInterval(timeid);
                             Ewin.alert({message: "Because you haven't operated for a long time, session Expired, Please login again"}).on(function (e) {
                                 window.location.href = "/iad/veiws/login/login.jsp";
                             })
                         }

                     }
                 });

             };

Summary: this method can extend the definition time by two seconds. First, your system should have a public page. Second, timing query may slow down the system

Posted by steelaz on Fri, 03 Apr 2020 21:40:17 -0700