Home > Article > Web Front-end > Jump to login page when session expires_html/css_WEB-ITnose
The project needs to have an automatic logout function. I checked the information on the Internet and initially planned to use session monitoring. Configure the listener as follows
1. In the project's web.xml Add the following code to the file:
?
3
4
|
|
2. Write a java class.
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class SessionListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent arg0) { // Executed when session is created SimpleDateFormat simpleFormat = new SimpleDateFormat("mm-ss-ms"); String nowtimes = simpleFormat.format(new Date()); User u=null; //System.out.println("Execute. . Current time: " nowtimes "_" u); HttpSession ses= arg0.getSession(); String id=ses.getId() "_" ses.getCreationTime(); } public void sessionDestroyed(HttpSessionEvent arg0) { // Executed when session fails SimpleDateFormat simpleFormat = new SimpleDateFormat("mm-ss-ms"); String nowtimes = simpleFormat.format(new Date()); //System.out.println("session has expired. End time: " nowtimes); } } |
1 2 3 4 5 6 7 8 | |
2. Create a new SessionFilter class and implement the Filter interface.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
public class SessionFilterimplements Filter { public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; "/admin/login.jsp"; String url = httpRequest.getRequestURI(); String path = url.substring(url.lastIndexOf("/")); // Timeout processing, ajax request timeout Set the timeout status. If the page request times out, a prompt will be returned and redirected if (path.indexOf(".action") != -1 // Determine whether it is an ajax request if (httpRequest.getHeader("x-requested-with") != null && httpRequest.getHeader("x-requested-with") .equalsIgnoreCase("XMLHttpRequest")) { . httpResponse.addHeader("loginPath", loginUrl); 🎜> String str = "";response.setContentType("text/html;charset=UTF-8");// Solve Chinese garbled characters Try { PrintWriter writer = response.getWriter(); writer.write(str); writer.flush(); writer.close(); (Exception chain.doFilter(request, response); } } @Override public void init(FilterConfig arg0) throws ServletException {
3. Client JS, used for ajax request session timeout For jquery
?
|