Recently, a JSP website encountered a session sharing problem. The following describes the details and solutions in a simple example:
The website has two domain names: the primary domain name www.test.com second-level domain name xxx.test.com
1. Use the primary domain name to open a website, such;
2. Perform the login operation and submit the form to www.test.com/checklogin.jsp. The two operations are performed in the same session (assuming the browser is not closed), why?
Because when we access other pages of the site through the primary domain, the JSESSIONID generated on the client in the first step is submitted to the server through the cookie method.
Used to obtain the corresponding session object. The two jsessionids are the same, so the two sessions are consistent.
3. log on to the www.test.com/index.jsp page and print the current JSESSIONID = xxxxxxxxxx.
4. access index. jsp through the second-level domain name, that is
On this page, the session has changed, that is, the access to the second-level domain name is invalid. Why? This is because the JSESSIONID generated by the primary domain cannot be obtained when index. jsp is accessed through this second-level domain name.
Therefore, a new session is generated and JSESSIONID = yyyyyyyyyy is saved to the client.
How can this problem be solved?
My solution: Create a jump page Skip. jsp
<% @ Page Language = "Java" contenttype = "text/html; charset = UTF-8" pageencoding = "UTF-8" %>
<%
String JSESSIONID = request. getsession (). GETID (); // obtain the current JSESSIONID (generated by access from the primary or secondary domains)
Cookie = new cookie ("JSESSIONID", JSESSIONID );
Cookie. setdomain (".test.com"); // the key is to set the cookie to the primary domain name for access, so that the cookie value can be obtained between different domains, so as to ensure session consistency
Response. addcookie (cookie); // return the cookie to the client
Request. getrequestdispatcher ("INDES. jsp"). Forward (request, response );
%>
NOTE: If any errors occur, please confirm your understanding of cookies and sessions!