Javaweb Session Conversation Management Example detailed _java

Source: Internet
Author: User
Tags flush session id send cookies sessions

Introduction to Session Sessions

A session is a process of interaction between a user using the same browser process and a Web application over a period of time.

Sessions are typically used to track the state of a user, caching the user's information in this browser process.

When the user closes the browser, the previous session is not available again (the maxage of the cookie is 1). Open a new browser again, and a new session will begin.

Class Javax.servlet.http.HttpSession. Each httpsession represents a user's session.
The expiration time for each session defaults to 30 minutes.

When the browser first accesses the server, the server assigns a unique session ID to the user, regardless of which page is first accessed, that is, Jsessionid and then returned to the user as a cookie.
The following figure is a response header (the following figure is based on Servlet3.0 and there is no httponly attribute in Servlet2.5)

The server creates a session for each user, that is, the HttpSession object, which is saved on the server side.

So how does the server know the current user when the user accesses the server again?

When the browser accesses the server again, it carries a cookie that contains the Jsessionid to access the server. The server returns the HttpSession object for this user based on this ID, and the session is maintained.
(So, can you implement the same session on a different browser?)

The following is a typical URL that has a certain amount of spoofing that enables the same session to be implemented on different browsers:

Http://localhost:8080/day07_2/CNCookieServlet;jsessionid=F8692D61CD46D094DBB7A8FC7387649C)

The relationship between the browser and the server is shown in two images:


HttpSession:

In the servlet, the Httpservletrequest.getsession method is used to get the session-like image.

The following methods of the HttpSession interface are used to share data within a session scope:

GetAttribute ("name")
setattribute ("name", object);
Getattributenames ()
removeattrubute ("name")

Invalidate (); -This method strongly deletes the session of the server cache.

Example:

Set certain values in a servlet's httpsession to the setattribute.

Through a hyperlink, or otherwise, go to another servlet and display the information through getattribute.

Call GetAttribute display information in any servlet.

Close this browser and reconnect to the servlet that gets the information, and you'll find no information.

As follows:

String name=request.getparameter ("name"); 
Request.setattribute ("name", "Request---" +name); 
Request.getsession (). setattribute ("name", "Session---" +name); 

Unique identification ID for session:

Each session is a unique identifier, or ID.

When the browser gets a new session, the user is able to print out the value of the ID by Session.geid ().

Jump on multiple pages without closing the browser, using the same session.

Such as:

 
 

What is a safe exit:

When a user exits, they should clear their information from the session-that is, a safe exit.

The safe exit is to clean up the information left on the server to prevent the black

Session.invalidate ();

1, Request.getsession (). invalidate ();

So that the corresponding objects in the session pool can be deleted

2, Session.removeattribute (...)

Such as:

Request.getsession (). RemoveAttribute ("Realcode");

Used to delete a property in a Session object

To track a session by overriding the URL:

As has been said before, the servlet container first saves a sessionid on the client and, later, when the browser makes an HTTP request, it will include this sessionid.servlet container to read the SessionID in the HTTP request. According to this SessionID, remove the httpsession from the container so that you can trace which session the HTTP request belongs to, a process called a session trace.

If the browser supports the Cookie,servlet container, the SessionID is saved as a cookie in the browser's client. But if the user disables cookies for security reasons, how does the Servlet container track the session?

First let's disable cookies in IE (note: It doesn't work for some ghost systems).

Ie> tools >internet options > Privacy > Advanced, and then disable cookies:

We can add such hyperlinks to the homepage: (Saveservlet.java getservlet.java Logoutservlet.java code associated with the following code I put on the last side)

 
 

This sentence <form action= "<%=response.encodeurl ("/AA ")%>" > can achieve this function

After the cookie is disabled, the browser can still receive the cookies sent by the server, but the browser can only accept that it cannot be sent to the server, and cannot send cookies to the session pool to retrieve the corresponding object.

The above code in the form to enter the desired value, and then to the following Getservlet here at the hyperlink to see if it is still able to display the input value, the answer is yes. The access path here is equivalent to a similar

Http://localhost:8080/day07_2/CNCookieServlet;jsessionid=F8692D61CD46D094DBB7A8FC7387649C, jsessionid= with the back. F8692D61CD46D094DBB7A8FC7387649C is its ID, so you can access it by entering the URL into another browser.
Here I want to add: (The following is when I write the HttpSession object in the session pool to the cookie in the Jsessionid value and value of the corresponding session, and this cookie overwrites the system-created one, which is equivalent to my own creation, I set the time to 10 minutes, if not covered, cookies will die when the browser is closed, the following phenomenon will not appear.

The ID of the newly created object in the session pool is not the same if you disable cookies, that is, if you enter a name value in the form when you disable the cookie, the query results are as follows:

and Jsessionid for 2bb51ebdeaaf14d19656c71e1b6f9ff6

Then immediately replace the cookie mode, enter another name like Tom, the result will naturally be two Tom,jsessionid

203F9E4DB5D874476B81DAF350661B6A, unlike disabling is not the same, which makes the following results appear

Then we closed the browser, went into the browser again, and looked at the results in cookie mode, as follows:

Below I post the main code:

Saveservlet.java

Package cn.hncu.servlets.session; 
Import java.io.IOException; 
Import Java.io.PrintWriter; 
Import javax.servlet.ServletException; 
Import Javax.servlet.http.Cookie; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest; 
Import Javax.servlet.http.HttpServletResponse; public class Saveservlet extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response 
) throws Servletexception, IOException {doPost (request, response); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {R 
Esponse.setcontenttype ("Text/html;charset=utf-8"); 
PrintWriter out = Response.getwriter (); 
Request.setcharacterencoding ("Utf-8"); 
String name=request.getparameter ("name"); 
Request.setattribute ("name", "Request---" +name); 
Request.getsession (). setattribute ("name", "Session---" +name); 
Getservletcontext (). setattribute ("name", "Application---" +name); Combine cookie technology with session technologyApplication of an example---※ function: Let the user after the browser is closed, if 10 minutes to login to the site, but also access to the information in the session/to the client write a key for "Jsessionid" with the value of SessionID cookies, 
Cookie C=new Cookie ("Jsessionid", Request.getsession (). GetId ()); 
C.setmaxage (60*10);//above phenomenon is caused by this sentence, without this sentence will not have the above mentioned phenomenon of C.setpath (Request.getcontextpath ()); 
Response.addcookie (c); 
Out.println ("Save success ..."); 
Out.flush (); 
Out.close (); } 
}

Getservlet.java

Package cn.hncu.servlets.session; 
Import java.io.IOException; 
Import Java.io.PrintWriter; 
Import javax.servlet.ServletException; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest; 
Import Javax.servlet.http.HttpServletResponse;  
public class Getservlet extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) 
Throws Servletexception, IOException {response.setcontenttype ("text/html;charset=utf-8"); 
PrintWriter out = Response.getwriter (); Out.println ("<! 
DOCTYPE HTML public \-//w3c//dtd HTML 4.01 transitional//en\ ">"); 
Out.println ("<HTML>"); 
Out.println (" 

Logoutservlet.java

Package cn.hncu.servlets.session; 
Import java.io.IOException; 
Import Java.io.PrintWriter; 
Import javax.servlet.ServletException; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest; 
Import Javax.servlet.http.HttpServletResponse; 
public class Logoutservlet extends HttpServlet {public 
void doget (HttpServletRequest request, HttpServletResponse Response) 
throws Servletexception, IOException { 
response.setcontenttype ("Text/html;charset=utf-8"); 
PrintWriter out = Response.getwriter (); 
Secure Exit---You can request.getsession () if the session object is invalid 
. Invalidate (); 
OUT.PRINTLN ("Safe exit ..."); 
} 

The above is a small set to introduce Javaweb session management, I hope to help everyone, if you have any questions welcome to my message, small series will promptly reply to everyone!

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.