(Javaweb series of reading notes) cookies and session

Source: Internet
Author: User

Cookies

1. HTTP protocol and Cookie (understanding)
* Cookies are made by the HTTP protocol! Cookies are saved to the browser by the server, and then the next time the browser requests the server, the last request is returned to the server.
* A key-value pair created by the server to be saved to the client browser! Server Save Cookie Response header: Set-cookie:aaa=aaa set-cookie:bbb=bbb
> Response.AddHeader ("Set-cookie", "Aaa=aaa") Response.AddHeader ("Set-cookie", "bbb=bbb");
* When the browser requests the server, the cookie saved by the server is sent to the server with the request. Browser return Cookie request header: COOKIE:AAA=AAA; bbb=bbb
* HTTP protocol provisions (guaranteed not to give the browser too much pressure):
> 1 Cookies Max 4KB
> 1 servers Save up to 20 cookies to 1 browsers
Up to 300 cookies can be saved in a > 1 browser
* Browser wars: Because the browser competition is very encouraging, so many browsers will violate HTTP rules within a certain range, but will not let a cookie be 4gb!


2. Use of cookies
* The server uses cookies to track client status!
* Save cart (items in cart cannot be saved with request because it is a user sending multiple request information to the server)
* Show last Login (also a user multiple requests)


Cookies are not cross-browser! ***********


3. Use of cookies in Javaweb
* Original Way (Learn):
> Send Set-cookie response headers using response
> Get cookie request header using request
* Convenient Way (Proficient):
> Use the Repsonse.addcookie () method to save cookies to the browser
> Use the Request.getcookies () method to obtain cookies returned by the browser


4. Cookie Explanation
* Cookies are not only name and value two properties
* MaxAge of cookies: The maximum life of a cookie, that is, the maximum amount of time a cookie can be saved. In seconds, for example: Cookie.setmaxage (60) indicates that the cookie will be saved to the hard drive by the browser for 60 seconds
> maxage>0: The browser will save the cookie to the client hard disk, and the valid length is determined by the value of MaxAge.
> Maxage<0:cookie only exists in the browser memory, and when the user closes the browser, the browser process ends and the cookie dies.
> maxage=0: The browser will immediately delete this cookie!
* Path (understanding) of cookies:
> The path of the cookie is not to set this cookie in the client's save path!!!
> Cookies are set when the path of the cookie is created by the server
> What cookies need to be returned to the server when the browser accesses a path on the server? This is determined by the path of the cookie.
> The path of the browser to the server, and if it contains the path to a cookie, the cookie will be returned.
> For example:
<> acookie.path=/day11_1/; bcookie.path=/day11_1/jsps/; ccookie.path=/day11_1/jsps/cookie/;
<> visit:/day11_1/index.jsp, return: Acookie
<> visit:/day11_1/jsps/a.jsp, return: Acookie, Bcookie
<> visit:/day11_1/jsps/cookie/b.jsp, return: Acookie, Bcookie, CCookie
> Cookie's path default: The parent path of the current access path. For example, when accessing/day11_1/jsps/a.jsp, the cookie's default path is/day11_1/jsps/
* Cookie Domain (Learn)
> domain to specify a cookie! Used when sharing cookies in multiple level two domains.
> For example, Www.baidu.com, zhidao.baidu.com, news.baidu.com, tieba.baidu.com sharing cookies can use domain
> Set Domain to: Cookie.setdomain (". baidu.com");
> Set Path to: Cookie.setpath ("/");


The cookie cannot exist in Chinese!!!


Save
Cookie C = new Cookie ("username", Urlencoder.encode ("Zhang San", "Utf-8"));//Error!
Response.addcookie (c);


Get
Cookie[] cs = request.getcookies ();
if (cs! = null) {
for (Cookie C:cs) {
if ("username". Equals (C.getname ())) {
String username = C.getvalue ();
Username = Urldecoder.decode (username, "utf-8");
}
}
}


============================================


HttpSession (* * * *)


1. HttpSession Overview
* HttpSession is a class that is provided by Javaweb for session tracking. Session is a server-side object, saved on the server side!!!
* HttpSession is one of the three major domain objects of the servlet (request, Session, Application (ServletContext)), so it also has setattribute (), getattribute (), RemoveAttribute () method
* HttpSession bottom-dependent cookie, or URL rewrite!


2. The role of HttpSession
* Session Scope: Session scope is a user starting from the first access server, to the end of the user close the browser!
> Session: A user-to-server multiple consistency request! The so-called coherence request is that the user has not closed the browser in the middle of multiple requests!
* The server will create a session object for each client, the session is like the client on the server side of the account, they are saved to a map server, the map is called the session cache!
> Servlet gets Session object: HttpSession session = Request.getsession ();
> JSP Gets the Session object: The session is under the JSP built-in object, without creating it can be used directly!
* Session Domain Related methods:
> void SetAttribute (String name, Object value);
> Object getattribute (String name);
> void RemoveAttribute (String name);


3. Case 1: Share data in multiple requests for sessions in the session
* Aservlet: Save data to Session field
* Bservlet: Get Data from session field
Presentation
> First Request: Access Aservlet
> Second Request: Access Bservlet


4. Case 2: Demo Save user login information (Proficient)
* Case-related pages and servlets:
> login.jsp: Login page
> succ1.jsp: Pages that can only be accessed if the login is successful
> succ2.jsp: Pages that can only be accessed if the login is successful
> Loginservlet: Verify that the user is logged in successfully!
* Each page and servlet content:
> login.jsp: Provide login form, submit form request Loginservlet
> loginservlet: Get request parameters to verify that the user is logged in successfully
<> failed: Save error message to request domain, forward to login.jsp (login.jsp display error message in Request domain)
<> Success: Save user information to session field, redirect to Succ1.jsp page, display user information in session field
> succ1.jsp: Gets the user information from the session domain and, if it does not exist, displays "You are not logged in". Presence Displays user information
> succ2.jsp: Gets the user information from the session domain and, if it does not exist, displays "You are not logged in". Presence Displays user information


As long as the user does not close the browser, the session will always exist, then the user information saved in the session will be there! Then user access to SUCC1 and SUCC2 will pass!

5. HttpSession principle (understanding)
* Request.getsession () Method:
> Get Jsessionid in Cookies:
<> If SessionID does not exist, create a session, save the session, and save the newly created SessionID in a cookie
<> if SessionID exists, find session object by SessionID, if not found, create session, save session, save newly created SessionID to cookie
<> if SessionID exists, the session object is found by SessionID, then the session object is no longer created.
<> Back to session
> If a new session is created, the browser will get a cookie containing SessionID, which has a life of-1, which exists only in the browser memory, and if the browser is not closed, the cookie persists.
> The next request, when the Request.getsession () method is executed again, because the session object can be found through the SessionID in the cookie, the same session object was used with the last request.

* The server will not create a session for you right away, it will not be created until the session is first acquired! Request.getsession ();


* Request.getsession (FALSE), request.getsession (True), request.getsession (), the latter two methods have the same effect,
> The first method: if there is no session in the session cache (if the cookie does not exist), then NULL is returned and the session object is not created.


6. HttpSession Other methods:
* String getId (): Get SessionID;
* int Getmaxinactiveinterval (): Gets the maximum inactivity time (in seconds) that the session can have and defaults to 30 minutes. 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 will be invalidated by the session, when the session expires, the client requests again, the server will create a new session to the client, and in response to the client's new session SessionID;
* Boolean isnew (): Check if session is new. When the client first requests, the server creates a session for the client, but at this point the server does not respond to the client, that is, when the SessionID is not responding to the client, the session state is new.


7. Maximum inactivity time for configuring the session in Web. xml
<session-config>
<session-timeout>30</session-timeout>
</session-config>


8. URL rewriting (understanding)


is to put all the pages in the path, all using Response.encodeurl ("..") Deal with it!

* The session relies on cookies to allow the client to return SessionID upon request, so that the corresponding session can be found
* If the client has disabled the cookie, then can not get SessionID, then the session is useless!
* URL rewriting can also be used to replace cookies
> Add a special request parameter to all hyperlinks and forms in the site, i.e. SessionID
> This allows the server to find the session object by obtaining SessionID from the request parameters.
* 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 do not rewrite! Of course the URL must be the URL to the site.






































(Javaweb series of reading notes) cookies and session

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.