The HttpSession of Javaweb

Source: Internet
Author: User
Tags set set uuid

Time: 2016-11-17-22:33

--httpsession

I. Overview of HttpSession
1. HttpSession is a class that is provided by Javaweb and used for session tracking.
2. The difference between session and Cookie
Session is a server-side object, saved on the server side, is provided by Javaweb, only Javaweb has.
Cookies are stored on the client and are provided by the HTTP protocol.
3. HttpSession is one of the three major domain objects of the servlet, so it also has the setattribute (), getattribute (), and RemoveAttribute () methods.
4, HttpSession bottom-dependent cookie or URL rewrite.

Second, the role of HttpSession
1. Session scope
A session scope is when a user starts from the first access server and ends with the user closing the browser.

2. Session
A user's multiple-consistency request to the server, the so-called coherence request, is that the user does not close the browser in the middle of multiple requests.

3, the server will create a session object for each client, they are saved to a map server, the map is called the session cache.
* Get Session object in Servlet: HttpSession session = Request.getsession ();
* JSP gets the Session object: The session is a JSP built-in object, you do not need to create it can be directly used.

4, the session domain related methods:
void SetAttribute (String name,object value)
Object getattribute (String name)
void RemoveAttribute (String name)

Iii. Case 1
To share data in multiple requests for sessions in the demo session
* Aservlet: Save data to Session field
A.JSP:

* Bservlet: Get Data from session field
B.JSP:

* Demo
First Request: Access Aservlet
Second Request: Access Bservlet
* If you do not close the current browser and open a new browser window, you can also access the session object in the b.jsp, or you can output "AAA"

Iv. Case 2
Demo Save User login information (must be mastered)
Problem:
Why does request redirection need to include a full servlet path?
Because the redirect is the client resending the request based on the URL, the URL needs to be rewritten.

1. Case-related pages and Servlets
* login.jsp: Login page
* successful1.jsp: A page that can only be accessed if the login is successful
* successful2.jsp: A page that can only be accessed if the login is successful
* Loginservlet.java: Verify that the user is logged on successfully

2. Each page and servlet content
* login.jsp: Provide login form, submit form request Loginservlet
* Loginservlet: Gets the request parameter, verifies whether the user is logged on successfully
Success: Save user information to session field, redirect to Successful1.jsp page, display user information in session domain.
Redirection is a client request, and the project name must be added.
Failure: Save error message to request domain, forward to login.jsp (login.jsp display error message in Request domain)
If you need to get parameters across requests, use the session, if only one request is required, using request, try to use a small range of domain objects.
* successful1.jsp: Gets the user information from the session domain, if it does not exist, displays "You have not logged in", the presence of the user information.
* successful2.jsp: Gets the user information from the session domain, if it does not exist, displays "You have not logged in", the presence of the user information.

As long as the user does not close the browser, the session will always exist, then the user information stored in the session exists, then the user
Access to successful1.jsp and successful2.jsp will be successful.

The code is as follows:
--------------------------------------------------------------------------------------------------------------- ---------------------------
login.jsp


<body>    <%--This page provides a login form with error messages--%>        <%--output error message--%>    <%        string ErrorMessage = "";       //Get error message in Request domain         String message = (String) reque St.getattribute ("errormessage");        if (message! = NULL)         {            errormessage = message;       }   %>    &LT ; font color= "Red" ><b><%=errormessage%></b></font>    <%-- Display the user name in the cookie to the username text box--%>    <form action= "/day11_3/loginservlet" method= "POST" >         user name: <input type= "text" name= "username" value= "<%=cusername%>"/><br/>         secret     code: <input type= "password" name= "password"/><br/>        <input type= "Submit" vale= "Login"/>    </form>&Lt;/body>

--------------------------------------------------------------------------------------------------------------- ---------------------------

Loginservlet.java

&NBSP;&NBSP;&NBSP;&NBSP;//1, getting form data     //handling coding issues      Request.setcharacterencoding ("Utf-8");     //Get parameters     string username = Request.getparameter ("username");     string password = request.getparameter ("password"); &NBSP;&NBSP;&NBSP;&NBSP;//2, verify user name and password     if ("admin". Equalsignorecase (username) && " Admin ". Equalsignorecase (password))     {        // Save the user name to a cookie and send it to the client browser         // When Login.jsp is opened again, Login.jsp reads the Cookie in the request and displays it in the User Name text box         cookie Cookie = new Cookie ("Cusername", username);//Create cookie         Cookie.setmaxage (60*60);         response.addcookie (cookie);//Save cookies, Will eventually become set Set-cookie header &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//3, login successful, saveInformation to session        httpsession session = Request.getsession ();// Get Session Object         session.setattribute ("username", username);// Save the user name in the session field         //Redirect to successful1.jsp         response.sendredirect ("/day11_3/session2/successful2.jsp");     }     else    {        //Logon Failure         //saving error messages to the request domain          request.setattribute ("ErrorMessage", "Username or password is incorrect");         // forward to Login.jsp        requestdispatcher rd = Request.getrequestdispatcher (" /session2/login.jsp ");//Get Forwarded Object         rd.forward (request, response);     }

--------------------------------------------------------------------------------------------------------------- --------------------------

successful.jsp

<body>
V. Principles of HttpSession

Session is saved on the server, and the SessionID is passed to the client via a cookie.

Request.getsession () method
1. Obtain the Jsessionid in the cookie:
* If SessionID does not exist, create a session, save the session, and save the newly created SessionID (jsessionid) in a cookie.
* If SessionID exists, find session object by SessionID, if not found, create session object, save newly created SessionID to cookie.
* If SessionID exists, the session object is not created by SessionID to find the session object.
* Returns the Session object.
2. If a new session is created, the browser will get a cookie containing the SessionID, the life of which is-1, which exists only in the browser memory, and the cookie persists if the browser is not closed.
3, the next time you request to execute the Request.getsession () method, because the session object can be found through the SessionID in the cookie, the same session object was used with the last request.
4, the server will not create the session immediately, but the first time (GetSession ()), the session object will be created.
5. If you visit a JSP page, the session object is created automatically because the session object is a JSP built-in object.

The difference between getsession (false), getsession (True), GetSession () methods:
GetSession (FALSE): If there is no session in the session cache (in the cookie), then NULL is returned and the session object is not created.

Vi. Other methods of HttpSession
String GetId ()
Gets the SessionID.

UUID: Generates a random, non-repeating, 32-bit-length, 16-character string.
UUID Code:
Get UUID Object

UUID uuid = Uuid.randomuuid ();            Converts a UUID object to a string, strings string = Uuid.tostring ();            Remove the "-" character string = String.Replace ("-", ""); Converts letters to uppercase String = String.touppercase ();

SessionID is obtained by means of a UUID.
SessionID can be placed in a cookie and sent to the client.

Question: What is the role of SessionID?


int Getmaxinactiveinterval ()
Gets the maximum inactivity time (in seconds) of the session, which defaults to 30 minutes, and when the session is not used within 30 minutes, Tomcat removes the session from the session pool.

void Invalidate ()
Let the session expire, call this method session will be invalid, when the session expires, the client requests again, the server will create a new session for this conversation, and in response to the client's new session SessionID. Can be used as an exit sign-in button.

Boolean isnew ()
To see if the session is new, when the client first requests it, the server creates a session for the client, but then the server does not respond to the client, that is, the session state is new when the SessionID is not responding to the client.
As long as the request does not have a cookie, the session is new. When the SessionID is sent to the client by the cookie, the client sends the request again, then the session is old.
This method can be used to determine whether to create a session or return Session:request.getSession (). IsNew ();

Vii. maximum inactivity time for configuring session in Web. xml
<session-config>
<session-timeout>30</session-timeout>
</session-config>

Eight, URL rewrite

is to use Response.encodeurl ("...") to process all hyperlink paths in the page.

1, the session relies on cookies, the purpose is to let the client make a request to return SessionID, so as to find its corresponding session.
2, if the client has disabled cookies, then can not get SessionID, so the session will not be used.
3. You can also use URL rewriting to replace cookies
* This allows you to add a special request parameter, SessionID, to all hyperlinks and forms in the site.
* This allows the server to find the session object by obtaining a SessionID from the request parameters.
4, Response.encodeurl (String URL)
* This method will intelligently rewrite the URL: When the request does not return SessionID this cookie, then the method will rewrite the URL, otherwise not rewritten.
* URL must be a URL pointing to this site.

The HttpSession of Javaweb

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.