A few days ago, I always wanted to implement the login persistence function, so I went to the Internet to read various materials. In the end, there are only several methods to achieve login persistence.
1. Save the information to the session
2. Save the information to the cookie (MD5 encryption can be used)
3. Extend the cookie Validity Period
The first operation is simple and easy to implement, but it has the disadvantage that persistence is only in one session, that is, when you turn off the page and re-open the page, it is found that the information has been cleared. This is obviously not suitable. The second approach is to store the user name and password (encrypted) into the cookie, and verify the cookie information each time for persistence. This is not a good solution. After all, it is insecure to store important information such as passwords in cookies.
I want to talk about the third method and the method that I think is the most feasible.
A session has a sessionid attribute to identify each user. Sessionid actually exists in the cookie. Therefore, you only need to lengthen the sesiionid's survival time in the cookie to achieve persistence.
There are two methods to access session or cookie in struts2:
1. pseudo access: implement the sessionaware interface (get session)
Cookiesaware interface (obtain cookie)
Cookieprovider interface (write cookie)
In addition, if you want to access the cookie, you must configure the interceptor in struts2.
<interceptor-ref name="defaultStack"></interceptor-ref><interceptor-ref name="cookieProvider"></interceptor-ref><interceptor-ref name="cookie"> <param name="cookiesName">ValidationMsg</param> <param name="cookiesValue">*</param></interceptor-ref>
However, this method cannot obtain the sessionid. Why?
Because it is a pseudo-access, a map is returned through this method. What is a map? It is a value pair, which simulates httpservletsession in this way.
Why?
You can only use httpservletapi at the price of coupling.
We only need to write as follows:
Httpservletresponse response = servletactioncontext. getresponse (); httpservletrequest request = servletactioncontext. getrequest (); httpsession session = request. getsession (); Session. setattribute ("username", user. getUserName (); string sessionid = session. GETID (); cookie = new cookie ("JSESSIONID", sessionid); // note that the key value must be the same as the original one; otherwise, the server cannot identify the user cookie. setmaxage (1*1800); // set the life cycle of cookie 1800scookie. setpath ("/"); response. addcookie (cookie); // cookie added
In this way, you can use cookie persistence to disable the page and log on automatically the next time you open the page.