HTTP itself is a stateless communication protocol, the basic principle of session management, is to maintain the status of the response to the browser, there is a browser on the next request to send the status information,
Let the Web Application "know" the association between requests.
The hidden field responds to the browser with input fields that the status information does not see in the form and sends these hidden input field values the next time the form is sent. A cookie is a small file saved in a browser,
You can set a lifetime, and when a browser requests a Web application, it sends a cookie that belongs to the Web site to the application. URL rewriting is to use hyperlinks and append information in the URL address of the hyperlink, in the way of Get
Request a Web application.
If you are creating a cookie, you can use the cookie class, create a name and value in the cookie, and use HttpServletResponse's Addcookie () method to add a cookie to the response.
You can use Setmaxage () to set a cookie's expiration date, and the cookie expires when you close the browser at preset time.
The getsession () that executes HttpServletRequest can obtain HttpSession objects. At the session stage, you can use the HttpSession setattribute () method to set the session to
Information can be obtained by using the GetAttribute () method. You can execute the invalidate () method if you want to invalidate the httpsession.
HttpSession is a Java object in a Web container, and each httpsession instance has a unique sessionid. The container defaults to using cookies to store SessionID in the browser, and on the next request,
The browser will send a cookie that includes SessionID to the application, and the application then obtains the corresponding HttpSession object based on the SessionID.
If your browser disables cookies, you cannot use cookies to store SessionID in your browser, and you can use the URL rewriting mechanism if you still intend to use HttpSession to maintain session information. HttpServletResponse
Encodeurl () method when a container cannot get sessionid from a cookie, the URL that is set to it is appended with SessionID to set the hyperlink information when the URL is rewritten.
HttpServletResponse's Encoderedirecturl () method allows you to ask the browser to redirect the page when the URL is appended with sessionid information.
Execute HttpSession's Setmaxinactiveinterval () method, setting the time at which the HttpSession object will expire when the browser is inactive, rather than storing the SessionID cookie expiration time.
The httpsession is used to maintain the state of the session, and if there is information, you want to use a cookie when you close the browser and you can still send it to the application the next time you open the browser to request the Web application.
1. Session Management Fundamentals:
The request and response of the Web application is HTTP-based, a stateless communication protocol, and the server does not "remember" the relationship between this request and the next request. However, some features
Must be done by multiple requests, such as shopping carts, where users may purchase goods between multiple shopping pages, the Web application must have a way to "know" that the user is in these
Which items are purchased in the Web page, this way of remembering the relationship between this request and the subsequent request is called Session management. (Session Management)
2. Basic ways to implement session management
In the HTTP protocol, the server does not have the memory function, each request is treated equally, according to the requested information to run the program and respond, each request to the server is a new request.
Basic ways to implement session management: 1. Hidden fields (Hidden field) 2.Cookie 3.URL rewrite (URL rewriting)
Web application session Management is the basic way, in this request, the next request when the server should know the information, first respond to the browser, the browser after the request again
Sent to the application so that the application can "know" the relevant data for multiple requests.
3. Hidden Domains for Session management
Related pages of continuity such as surveys.
The current page requires the previous page access, you can pass a <input type= "hidden" > The hidden domain to the next page, Xunhua recursive delivery, know the end to maintain the entire process of session management.
The hidden domain is not a mechanism for servlet/jsp actual session management, and there are browsers that proactively inform the necessary information for implementing the Fundamentals of Web application Session management.
4.Cookie for Session Management
A cookie is a way of storing information in a browser, and the server responds to the browser Set-cookie header, which is stored on the computer as a file after the browser receives the header and value.
This file is called a cookie. You can set the cookie to a survival period, retain some useful information on the client, if the browser is closed after you open the browser again and connect to the server, these cookies
Still in the validity period, the browser uses the cookie header to automatically send the cookie to the server, and the server learns some information about previous browser requests.
5.URL rewrite (URL rewriting) is actually the application of the GET request parameter, when the server responds to the browser's last request, some relevant information is hyperlinked to the browser, including the request parameter information in the hyperlink.
Because URL rewriting is a way to append information after a hyperlink, a request must be sent in a Get mode, plus a limited length of request parameters that can be carried by the get itself, so a large amount of client information is reserved and is not intended for use with URL rewriting.
Usually URL rewriting is used in some simple client information retention, or as a secondary session management.
6.HTTPSession Session Management
The basic way of three session management above. In either case, the response to the browser must be handled on its own, deciding what information must be sent to the browser in order to send the relevant information in a future request for the Web application to identify the request
Association between the two.
It is convenient to use HttpSession for session management, so that Web applications appear to "Remember" the requests made by the browser and connect the relationships between several requests. However, the fact that the Web application is based on the HTTP protocol has not changed,
Actually how to "know" the relationship between several requests, the job is to have a Web container to help you execute. When you try to run HttpServletRequest's getsession (), the Web container creates HttpSession objects, the key is
Each HttpSession object will have a special ID called sessinoid, and you can execute HttpSession's getid () to get SessionID. This sessionid is stored by default in the browser using a cookie.
In Tomcat, the name of the cookie is Jsessionid, and the value is the SessionID obtained by GetID ().
Since the Web container itself is executed in a Java program in the JVM, the properties stored in the httpsession are naturally stored in the server-side Web container by acquiring the HttpSession object through GetSession (). Each one
HttpSession each have a special SessionID, when the browser requests the application, the SessionID stored in the cookie will be sent to the application, the Web container will be based on SessionID to find the corresponding httpsession
Object so that you can get the session data for each browser.
So when using HttpSession for session management, objects set as properties are stored on the server side, while SessionID is stored on the browser side by default using cookies. The Web container stored in the SessionID cookie "default" is
Closing the browser fails, so when restarting the browser requesting the application, the new HttpSession object is obtained through GetSession ().
Each time the request arrives at the application, the container obtains the corresponding httpsession based on the SessionID sent. Because the HttpSession object takes up memory space, the properties of the HttpSession do not store the consumed resources as much as possible.
Large objects, when necessary to remove attributes, or do not need to use httpsession, the execution of invalidate () to invalidate httpsession.
By default the browser will be immediately aging is the browser cookie, cloth is httpsession. Because the cookie fails, it is not possible to send the SessionID through a cookie, so when trying to getsession (), the container generates a new
The HttpSession object. In order for the httpsession to fail immediately, the invalidate () method must be run, otherwise the httpsession will wait until after the set expiration period to be destroyed by the container.
Can execute the httpsession Setmaxinactiveintervale () method, set the browser for how long without the request application, HttpSession will automatically expire, set the unit is "seconds."
Using HttpSession, the default is to use a cookie to store SessionID, but you do not have to intervene in the details of the cookie, and the container will help you with the operation. In particular, the implementation of the HttpSession Setmaxinactiveinterval () method,
setting is the time at which the HttpSession object expires when the browser is inactive, rather than storing the SessionID cookie expiration time. Cookies that store SessionID are disabled by default and are only used to store session IDs.
HttpSession with URL rewriting
HttpSession uses cookies to store SessionID by default, and if a user turns off the browser to accept cookies, they cannot use cookies to store SessionID in the browser. If you still intend to use HttpSession if you disable cookies
For session management, you can use URL rewriting to respond to a hyperlink to the browser, append sessionid after the hyperlink URL, and send SessionID as a GET request to the Web application when the user clicks the hyperlink.
If Encodeurl () is executed, the container does not know when the browser first requests the Web site that the cookie is disabled, so the container practices the cookie (sending the Set-cookie header) with the URL rewrite method, so if the servlet has the following statement, The URL of the SessionID is displayed on the first request, regardless of whether the browser has a cookie disabled:
Reqeust.getsession (); Response.encodeurl ("Mysessionservlet") (Must have jsessionid for the first time)
Example: Http://localhost:8080/servlet-demo/mySessionServlet;jsessionid=90A1530600E82E2BDD8E51DB0D7151AE
When requested again, if the browser does not disable cookies, the container can obtain SessionID from the cookie (from the cookie header), then Encodeurl () will only output http://localhost:8080/servlet-demo/ Mysessionservlet
If cookies are disabled, the Encodeurl () will show Jessionid if the cookie is not sessionid.
In summary, when a container tries to obtain a HttpSession object, SessionID cannot be obtained from the cookie, and Encodeurl () generates a SessionID URL so that SessionID is sent again the next time you click the hyperlink. Another httpservletresponse
On the Encoderedirecturl () method, you can display SessionID on the URL when you require browser redirection.
Keep SessionID carefully. During HttpSession survival, the same HttpSession object can be obtained as long as someone obtains the current SessionID and the same URL in another browser is appended with SessionID.
It is recommended to encrypt sensitive information and perform invalidate () when not using HttpSession to invalidate it explicitly. Session phase of the important operation, it is best to do another identity verification (such as the online transfer before the transfer password);
Package Com.zghw.servlet.demo;import Java.io.ioexception;import Java.io.printwriter;import Java.text.simpledateformat;import Java.util.date;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.cookie;import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;/** * Cookie principle Since HTTP is stateless, once accessed, it is not possible to remember whether the last client browser accessed was the same client browser as this time. * In order to realize the same client browser to do some business needs, such as browsing historical merchandise records, can be implemented using the cookie technology provided by the servlet. * * When the client browser sends a request to come over, after the business processing, can respond to the client browser a cookie, this value is set in the response header of the Set-cookie *, the client browser receives this Set-cookie will be stored on the computer as a file. This file becomes a cookie. * * When a client browser sends a request, it will also send a cookie that exists on the site to the Set-cookie of the request header, and the server can cycle the cookie * collection to query the required cookie for processing. * * Cookie limit, a browser up to 300cookies, a Web site, up to 20cookie, and a cookie size limit in 4k * */@WebServlet ("/mycookiesservlet") public Class Mycookiesservlet extends HttpServlet {private static final long Serialversionuid = 1l;private static final String LA Sttime = "Lasttime";/** * Simulates the most recent access time */protected void doget (httpservletrequest request,httpservletresponse response) throws Servletexception, IOException {response.setcontenttype ("text/html;charset=utf-8"); PrintWriter out = Response.getwriter (); Boolean isFirst = true;//A collection of cookies sent by the client browser via request requests cookie[] cookies = Request.getcookies (); if (cookies! = null) {for (Cookie cookie:cookies) {if (Lasttime.equals (Cookie.getname ())) {//update last visited Ask time, when the cookie is already present on the client, the new cookie value will overwrite the cookie value addcookielasttime (response); IsFirst = False;out.print ("Last Access time:" + Cookie.getvalue ());}}} if (IsFirst) {addcookielasttime (response); Out.print ("You are the first to visit!") ");}} private void Addcookielasttime (HttpServletResponse response) {SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss "); String now = Sdf.format (New Date ());//Create cookie Object Cookie cookie = new Cookie (lasttime, now);//Set cookie survival time, 0 forever Cookie . setmaxage (3600 * 24 * 7);//set to respond to the response object, send the cookie to the client browser to save it in the client file Response.addcookie (cookie);} /** * */protected void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException {this.doget (Request, response);}}
Package Com.zghw.servlet.demo;import Java.io.ioexception;import Java.io.printwriter;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import javax.servlet.http.httpsession;/** * Session Use example when trying to run HttpServletRequest's getsession (), the Web container creates a HttpSession object, the key is * Each HttpSession object will have a special ID called Sessinoid, you can execute HttpSession getid () to get SessionID. * This sessionid is stored by default in the browser using a cookie. * In Tomcat, the name of the cookie is Jsessionid, and the value is the SessionID obtained by GetID (). * Because the Web container itself is executed in a Java program in the JVM *, the HttpSession object is obtained through GetSession (), and the properties stored in the httpsession are naturally stored in the server-side Web container. Each * HttpSession has a special SessionID, when the browser requests the application, the SessionID stored in the cookie will be sent to the application, * the Web container will find the corresponding httpsession according to SessionID Object so that you can get the session data for each browser. * So when using HttpSession for session management *, objects set as properties are stored on the server side, while SessionID default cookie is stored on the browser side. The Web container stored in the SessionID cookie "default" is * closed browser is invalidated, so when restarting the browser requesting the application, the new HttpSession object is obtained through GetSession (). */@WebServlet ("/Mysessionservlet ") public class Mysessionservlet extends HttpServlet {private static final long Serialversionuid = 1l;prot ected void doget (httpservletrequest request,httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter pw = Response.getwriter ();//Get HttpSession object by request HttpSession session = (HttpSession) Request.getsession ();//Gets the value stored in the HttpSession object in the integer in = (integer) session.getattribute ("Count"); if (in = = null) {// Each time a browser is reopened, a new session object is re-opened, which corresponds to the new SessionID, which is stored in the browser-side cookie, and/or the SessionID persists until the end of the expiration time as long as the browser does not close. in = 0;pw.print ("First access from Session");} else {in++;p w.print ("from session" + In + "secondary Access");} Pw.print ("sessionid=" + Session.getid ());//Session object creation time Long createtime = Session.getcreationtime ();// Whether the session object is the first to create a Boolean isnew = Session.isnew ();p w.print ("The current session object is the first time:" + isnew);p w.print (" The first creation time of the current session object: "+ createtime";//Set the value in the HttpSession session.setattribute ("Count", in);//Set the session's expiration time in units ofThe second 0 is never invalidated unless you call invalidate, or close the browser session.setmaxinactiveinterval (1800);//Session object destruction//Session.invalidate ();// When a user disables cookies, a new session object is created each time//If you do not use Response.encodeurl to generate the URL of the hyperlink, the program will fail if the browser disables the cookie, that is, the heavy but incremental link,// The counter also does not increment//if the Encodeurl () is executed when the browser first requests the site, the container does not know the browser when the cookie is disabled, so the container practices when the cookie (send Set-cookie header) and//url overrides the way that Therefore, if the servlet has the following statement, regardless of whether the browser has a cookie disabled, the first request will be displayed in SessionID url://reqeust.getsession (); Response.encodeurl (" Mysessionservlet ")//pw.print (" <a href= "" +response.encodeurl ("Mysessionservlet") + "' > Increment </a>");} protected void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException { Doget (request, Response);}}
HTTP Session Cookie Session