Solve the Problem of J2EE-session failure after the browser is closed, j2ee-session failure

Source: Internet
Author: User

Solve the Problem of J2EE-session failure after the browser is closed, j2ee-session failure

A few days ago, when I was running a sign-in system, I encountered a very popular session problem. The project is Spring + SpringMVC + Mybatis framework, and the Java Web Terminal System of maven management directory. For some session problems, make the following analysis. Here, we will focus on the session lifecycle. For other definitions, we will not explain them:

First, describe the session lifecycle:

Storage: sessions are stored on the server. Generally, to prevent high-speed access in the server's memory, Sessinon is created when the user accesses the server for the first time, you must note that the Session will be created only when you access JSP, Servlet, and other programs. The Session will not be created only when you access static resources such as HTML and IMAGE. In a Java Web application, you can callRequest. getSession (boolean xxx)Generate a Session. Note: When the boolean parameter is true, a new session is forcibly generated here.

1. session expiration time:

The last time the session was used to reach the set expiration time, the session becomes invalid.

2. Another method is that session. invalidate () is executed and takes the initiative to invalidate the session.

For the expiration time, you can configure the attributes in web. xml to define the expiration time:

<Session-config> <session-timeout> expiration time </session-timeout> </session-config>

The unit of expiration time is minute. To set the validity period of a session to one day, it can be set to 60*24. When it is set to 0 or a negative number, the session is permanently valid, according to the definition of the expiration time, it is easy to understand this situation.

Why does the session expire after the browser is closed?

  • No session expiration time is set. By default, the session becomes invalid after the browser is closed;
  • Most session mechanisms use cookies in the process to save sessionid, that is, JSESSIONID. After the browser is closed, the process disappears and the cookie in the process disappears, the sessionid disappears.

A simple example is provided based on the known content:

@ Controllerpublic class SessionTest {@ RequestMapping ("/sessionTest") public String sessionTest (HttpServletRequest request, HttpServletResponse response) {System. out. println ("success! "); HttpSession session = request. getSession (); session. setMaxInactiveInterval (259200); request. setAttribute ("creationtime", session. getCreationTime (); // creation time request. setAttribute ("id", session. getId (); // id request. setAttribute ("max", session. getMaxInactiveInterval (-1); // maximum expiration time // here, MaxInactiveInterval takes precedence over web. session-cofig in xml, in the unit of second request. setAttribute ("lasttime", session. getLastAccessedTime (); // The last time the request was used. setAttribute ("sessionTest", session); // System. out. println (session. getCreationTime (); // System. out. println (session. getMaxInactiveInterval (); // System. out. println (session. getLastAccessedTime (); return "page/showSession" ;}< table border = "1" cellspacing = "0" cellpadding = "0"> <tr> <td> Creation Time: </td> <td >$ {creationtime} </td> </tr> <td> id: </td> <td >$ {id} </td> </tr> <td> maximum survival time: </td> <td >$ {max} </td> </tr> <td> last use time: </td> <td >$ {lasttime} </td> </tr> <td> session: </td> <td >$ {sessionTest} </td> </tr> </table>

Resolution:

  • The above code simulates a logon. In the controller, an HttpSession object is created and all the parameters that can be set are basically set,
  • However, when the browser is closed and you enter the home page again, you still need to log on again, indicating that the browser did not get the session object again, you can go to chrome Settings> Advanced Settings> privacy settings> all cookies and website data, and search for the local tomcat server to view the saved session, that is, a cookie named JSESSIONID.


It can be seen that the session expiration time is still when the browser is closed, so only when the browser does not close the access again can the login status continue to be used, what exactly is the expiration time we set above?

A Session is created between the browser and the server. Because the client does not interact with the server for a long time (sleep time), the server destroys the Session, when the client interacts with the server again, the previous Session does not exist. In my understanding, the expiration time only takes effect in one Session. If the browser is closed, the Session ends, in fact, the expiration time is set to permanently valid, that is, when the browser is closed and the session is closed. To solve this problem, we can mix cookies with sessions. There is such a stupid way:

Actively add cookies and set the directory to be saved and time to live

public static void addCookie(String name, String value, int age, HttpServletResponse response) throws   UnsupportedEncodingException {  Cookie c = new Cookie(name, URLEncoder.encode(value, "utf-8"));  c.setMaxAge(age);  c.setPath(path);  response.addCookie(c); }

UseCookie[] cookies = request.getCookies();Traverse the cookie and obtain the desired cookie Based on the cookie name. It can also be called the session. Finally, the desired result is obtained. The session (the cookie named JSESSIONID) escaped the browser's imprisonment.

Summary

The above is a small series to introduce you to solve the problem of failure after the browser closed, I hope to help everyone, if you have any questions, please leave a message for me, xiaobian will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.