This is the 6th day of my participation in the August More Text Challenge
The HttpSession:
1. The most common HttpSession method is the domain method.
2. Summary of the HttpSession.
* javax.mail servlet. HTTP. The HttpSession interface represents a session, we can put inside a session to share data saved to the HttpSession object! \ * HttpSession is a class provided by JavaWeb for session tracking. Session is a server-side object, stored on the server side!! HttpSession is one of the three Servlet domain objects (Request, Session, Application (ServletContext)). So it also has setAttribute(), getAttribute(), removeAttribute() methods \ * HttpSession base depends on cookies, or URL rewriting!Copy the code
Get the HttpSession object:
(1HttpSession request.getsesssion () : returns if the current session already has a session object. If the current session does not already have a session object, creates a session and returns it. \ [2)HttpSession Request. getSession(Boolean) : When the parameter istrueIs the same as requeset.getSession(). If the parameter isfalseIf there is a session in the current session, the return is returnednull;Copy the code
4. What HttpSession does:
1.Session scope: The session scope starts when a user accesses the server for the first time and ends when the user closes the browser!2.Sessions: multiple sequential requests from a user to the server! A continuous request is when the user makes multiple requests without closing the browser!3.The server creates a session object for each client. A session is like the client's account on the serverMapIn theMapIt's called session caching!4.Session = request.getSession();5.Get session object in Jsp: Session is under Jsp built-in object, do not need to create can be used directly!6.Session domain: >void setAttribute(String name, Object value);
> Object getAttribute(String name);
> void removeAttribute(String name);
Copy the code
HttpSession is a domain object:
We’ve looked at HttpServletRequest, ServletContext, which are domain objects, and now we’ve looked at HttpSession, which is also a domain object. Three of these are domain objects that can be used in servlets, and one more domain object can be used in JSPS, the fourth of which we’ll cover tomorrow.
(1) it: A request creates a request object, so a request can be shared within the same request. For example, if a request is forwarded from AServlet to BServlet, AServlet and BServlet can share data in the request domain. (2HttpSession: An HttpSession object is created for each session. Data in the session can be shared between multiple requests in the same session. (3)ServletContext: An application creates only one ServletContext object, so the data in the ServletContext can be shared across the application, as long as the server is not started.Copy the code
Download is the domain method of session:1)void setAttribute(String name, ObjectValue) : Stores an object, or a domain attribute, for example, session.setattribute (" XXX ", "XXX"). A domain attribute is saved in the session. The name of the domain attribute is XXX, and the value of the domain attribute is XXX. Note that if the method is called multiple times with the same name, the last value is overwritten, which is the same asMapThe same; (2)Object getAttribute(StringName) : used to retrieve session data. Currently, it needs to be stored before retrieving data. For example:String value = (String) session. The getAttribute (" XXX "); , get the domain property named XXX; (3)void removeAttribute(StringName) : removes domain attributes from HttpSession. If the name parameter does not exist, this method does nothing. (4)Enumeration getAttributeNames() : Gets the names of all domain attributes;Copy the code
6. HttpSeesion principle:
The session base relies on cookies! Let’s understand how sessions work.
1. When I went to the bank for the first time, I didn’t have an account yet, so I needed to open an account. What I got was a bank card, but my account number was left in the bank database. When I go to the bank again, I only need to bring my card instead of opening an account number. As long as take my card, so I in the bank operation must be my account number!
2. When a session is used for the first time, the server creates a session. The session is stored on the server and the session ID is given to the client (a cookie saves the session ID). The client takes away the sessionId and the data is stored in the session. When the client accesses the server again, the sessionId is included in the request, and the server uses the sessionId to find the corresponding session without creating a new session.
3.* request.getSession() :
> get JSESSIONID in Cookie: <> If the sessionId does not exist, create a session, save the session, save the newly created sessionId in the Cookie <> If the sessionId exists, use the sessionId to find the session object, if not found, Create a session, save the session, save the newly created session ID in the Cookie <> If the session ID exists and the session object is found by the sessionId, then the session object will not be created. <> Return session > If a new session is created, the browser gets a Cookie containing the sessionId with a lifetime of -1, that is, only in the browser memory, if the browser is not closed, then the Cookie is always there. > When the request.getSession() method is executed again on the next request, the same session object is used because the session object can be found through the sessionId in the Cookie. * The server will not create a session for you immediately, it will create a session the first time you acquire it! request.getSession(); * request.getSession(false), the request. GetSession (trueRequest.getsession (); request.getSession(); request.getSession();falseThis method returns if there is no session in the session cache (if the cookie does not exist)nullWithout creating a session object.Copy the code
4. Session and browser:
The session is stored on the server, while the sessionId is sent to the client via a Cookie, but the Cookie's life is not -1In other words, if the user closes the browser, the Cookie is lost. When the user opens the browser and accesses the server again, no session ID will be sent to the server, so the server will assume that you don't have a session, so the server will create a session and send the Cookie in the session ID to the client in the response. You might say, well, what about the original session object? When a session is unused for a long time, the server deletes the session! This duration is configured in Tomcat30This configuration can be found in ${CATALANA}/conf/web.xml, or you can override it in your own web.xml! web.xml <session-config><session-timeout>30</session-timeout></session-config> </session-config> If you open a page of the site and start to freeze for a long time, go beyond30Minutes later, when you click on the link or submit the form again, you will find that your session has been lost!Copy the code
5.HttpSession other methods
(1)StringGetId () : obtains the sessionId. (2)int getMaxInactiveInterval() : obtains the maximum inactivity duration (seconds) of a session. The default value is30Minutes. When the session30Tomcat removes the session from the session pool if it is not used within a minute. (3)voidInvalidate () : Invalidate session! When a session expires, the server creates a new session for the client and gives the sessionId of the new session to the client in the response. For example, the push button, when the user clicks the exit button hyperlink, then invokes the session invalidate method in the Servlet to charge the session away. And then we can derive it. (4Boolean isNew() : checks whether the session isNew. When the client requests the session for the first time, the server creates a session for the client, but the server has not responded to the client, that is, has not responded to the client with the sessionId, then the session state is new. Request. GetSession. isNew(); Two purposes: One is to create a session. The second is to find the original session and return it. You can tell if it's a new session.Copy the code
6. Set the maximum inactivity time of a session in web. XML:
Configure maximum inactivity time in web.xml <session-config><session-timeout>30</session-timeout>
</session-config>
Copy the code
7. The URL rewrite:
We know that sessions rely on cookies, so why do sessions rely on cookies? Because the server needs to get the sessionId on each request and then find the client’s session object. What if cookies are turned off in the client browser? Does that mean that session doesn’t exist? In fact, there is a way to make the server receive every request with sessioinId, that is URL rewrite! Add a parameter named jSessionId to each link and form on each page with the value of the current sessionid. When a user clicks on a link or submits a form, the server can also get the client sessionId by getting the jSessionId parameter and finding the sessoin object. The idea is to turn urls into request parameters. \
Index. The JSP < body ><h1>The URL rewrite</h1>
<a href='/day06_5/index.jsp; jsessionid=<%=session.getId() %>' >The home page</a>
<form action='/day06_5/index.jsp; jsessionid=<%=session.getId() %>' method="post">
<input type="submit" value="Submit"/>
</form></body> can also be used for each requested URL using Response.encodeURL (), which will automatically append the JsessionID parameter as we did manually above. <a href='<%=response.encodeURL("/day06_5/index.jsp") %>'> home page < / a ><form action='<%=response.encodeURL("/day06_5/index.jsp") %>' method="post">
<input type="submit" value="Submit"/>
</form>
Copy the code
Using Response.encodeURL () is more “smart” in that it determines whether the client browser has cookies disabled and if so appends the JsessionID to the URL, otherwise it doesn’t. Response.encodeurl (“..”) ) Deal with it!
* If cookies are disabled, the session id cannot be returned, and the session is useless! * You can also use URL rewriting instead of Cookie > to add a special request parameter to all hyperlinks and forms of the website, namely sessionId > so that the server can obtain the sessionId from the request parameter, so as to find the session object. * response.encodeURL(StringUrl) > this method does an intelligent rewriting of the URL: if the cookie sessionID is not returned in the request, this method will rewrite the URL, otherwise it will not rewrite! Of course, the URL must be the URL pointing to this site. <a href="/day_3/AServlet; JSESSIONID=<%=session.getId()%>"> Click here </a><a href="/day_3/AServlet; JSESSIONID=<%=session.getId()%>">Click here to</a>
<a href="/day_3/AServlet; JSESSIONID=<%=session.getId()%>">Click here to</a>
// It checks to see if the cookie exists, and if not, adds the jsession argument \ to the specified URL
// If it exists, it will not add anything after the URL \
out.print(response.encodeURL("/day11_3/AServlet"))
Copy the code