JavaWeb Session failure time setting method

  • 2020-05-26 09:15:01
  • OfStack

The failure time setting method of session is as follows:

1. java code < ! -- the priority is highest -- >


request.getSession().setMaxInactiveInterval(1800);/* In seconds, 1800= 60*30  namely 30 minutes */

2. web.xml < ! -- the lowest priority -- >


<session-config>  <!-- Minutes in units -->
  <session-timeout>30</session-timeout>
</session-config>

3. web server resin.conf, tomcat,


<session-config>  <!-- Minutes in units -->
  <session-timeout>30</session-timeout>
  <enable-url-rewriting>false</enable-url-rewriting>
</session-config>

Priority: 1 > 3 > 2

session will not normally fail after rebooting tomcat, and session will fail after closing the browser

In a type 1 system, some operations may also be required after the failure of session:

(1) control the number of users. After the failure of session, the number of users of the system will be reduced by 1. Control the number of users within 1 set range to ensure the performance of the system.

(2) control one user to log in for multiple times. When session is valid, if the same user logs in, it will be prompted to log in. When session is invalid, it can log in without prompting.

So how do I perform series 1 operations after session failure?

This is where the listener comes in. When the session fails for various reasons, the listener can listen, and then execute the program defined in the listener.

The listener class is: HttpSessionListener class, yes sessionCreated 和sessionDestroyed Two methods

You can inherit this class and implement it separately.

sessionCreated refers to the method that is executed when session is created

sessionDestroyed refers to the method executed when session fails

As follows:


public class OnlineListener implements HttpSessionListener{   
   public void sessionCreated(HttpSessionEvent event) {   
      HttpSession ses = event.getSession();   
      String id=ses.getId()+ses.getCreationTime();   
      SummerConstant.UserMap.put(id, Boolean.TRUE);   // Add user    
    }   
    public void sessionDestroyed(HttpSessionEvent event) {   
      HttpSession ses = event.getSession();   
      String id=ses.getId()+ses.getCreationTime();   
      synchronized (this) {   
        SummerConstant.USERNUM--;      // Users to reduce 1   
        SummerConstant.UserMap.remove(id); // Removed from the user group, the user group is 1 a map   
     }   
    }   
 }

Just declare this listener in web.xml:


<listener>   
  <listener-class>com.demo.system.listener.OnlineListener</listener-class>   
</listener>

The above is a simple way to monitor the number of users using session. In practice, it may be much more complicated than this.

For example, ServletContextListener and HttpSessionListener interfaces should be implemented simultaneously, and their methods should be overwritten.


Related articles: