Session cookie in Servlet (7), servlet session cookie

Source: Internet
Author: User

Session cookie in Servlet (7), servlet session cookie
1. (1). the user outputs the URL address to effectively access a website and perform a series of valid operations on the website. Then, the entire process of closing the browser is called a session.
(2) sessions mainly solve how the server stores the private information of each client.
(3) There are two main types of sessions:
A> Cookie technology [Client technology]

B> Session Technology

The difference between the two is that the session will expire with the browser closed, but the cookie will be stored on the client machine until the Cookie lifecycle is exceeded.

2. Cookie technology

(1) Cookie is a client technology. The server sends the data of each user to the user's browser in the form of a cookie. When a user uses a browser to access the web resources on the server, the user will carry their own data. In this way, web resources process user data.
(2) One Cookie can store only one type of information.
(3) update a Cookie with the same name, that is, write a Cookie with the same name to the browser.
(4) The Cookie must be valid for a period of time. If this parameter is not set, the Cookie is automatically destroyed after the request is accessed by default, the default Cookie validity period ends when a valid session ends.

3. Cookie Comprehension







4. Notes for cookies:

(1) A Cookie can only identify one type of information. It contains at least one NAME and VALUE ).
(2) a web site can send multiple cookies to a WEB browser. a web browser can also store the cookies provided by multiple WEB sites.
(3) browsers generally only allow 300 cookies, and each site can store up to 20 cookies. The size of each Cookie is limited to 4 kb.
(4) If a cookie is created and sent to the browser, It is a session-level cookie (that is, stored in the browser's memory) by default ), the user is deleted after exiting the browser. If you want your browser to store the cookie on a disk, you need to use maxAge and provide a time in seconds. If the maximum validity period is set to 0, the browser deletes the cookie.
Note: When you delete a cookie, the path must be consistent; otherwise, the cookie will not be deleted.


5. Small code exercises:

Package cn. wwh. www. web. cookie; import java. io. IOException; import java. io. printWriter; import java.net. URLDecoder; import java.net. URLEncoder; import javax. servlet. servletException; import javax. servlet. http. cookie; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse;/*** class: used to create cookies and obtain data values. Note 1. make a non-empty judgment on the returned cookie * 2. For the encoding method using the UTF-8 method, the running result is abnormal, * while the use of gbk method but normal output, it is very strange, (English do not need to transcode) * ** @ author yiye Binzhou * @ version 1.0 * @ Creation Time: 04:52:31 */public class CreateCookie extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// create a CookieCookie name = new Cookie ("name", URLEncoder. encode ("", "gbk"); // set the cookie survival time name. setMaxAge (1 * 24*60*60); // The server writes the cookie to the client's cache in response. addCookie (name); // retrieve all cookiecookies on the client [] allCookie = request. getCookies (); Cookie nameCookie = null; if (allCookie! = Null) {for (Cookie cookie: allCookie) {System. out. println ("cookieName:" + cookie. getName (); if (cookie. getName (). equals ("name") {nameCookie = cookie; break ;}}// output cookie information System. out. println ("cookie name:" + nameCookie. getName (); System. out. println ("cookie value:" + URLDecoder. decode (nameCookie. getValue (); System. out. println ("cookie version:" + nameCookie. getVersion (); System. out. println ("cookie path:" + nameCookie. getPath (); System. out. println ("cookie survival time:" + nameCookie. getMaxAge ());}}


6. Code Exercise 2:
Package cn. wwh. www. web. cookie; import java. io. IOException; import java. util. date; import javax. servlet. servletException; import javax. servlet. http. cookie; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse;/*** class function: use cookie technology to display the last access time of a user. *** @ author: 2014-8-1 08:38:14 */public class ShowVisitedTim E extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String name = request. getParameter ("name"); if (name = null) {name = "default" ;}// obtain the client's cookieCookie [] cookies = request. getCookies (); if (cookies = null) {Cookie nameCookie = new Cookie ("name _" + name, System. currentTimeMillis () + ""); // set the cookie cache time to one hour nameCook Ie. setMaxAge (1*60*60); // write to the client's cache response. addCookie (nameCookie); response. setContentType ("text/html; charset = UTF-8"); response. getWriter (). write ("welcome" + "your first visit to this website. The current time is:" + new Date (). toLocaleString ();} else {Cookie c = null; for (Cookie cookie: cookies) {// you have logged on to if (cookie. getName (). equals ("name _" + name) {c = cookie; break ;}} if (c! = Null) {response. setContentType ("text/html; charset = UTF-8"); // get the last access time String lastTimeStr = c. getValue (); Long lastTime = Long. parseLong (lastTimeStr); response. getWriter (). write ("welcome" + "you visit this website again. The last access time is:" + new Date (lastTime ). toLocaleString (); Cookie nameCookie = new Cookie ("name _" + name, System. currentTimeMillis () + ""); // set the cookie cache time to one hour nameCookie. setMaxAge (1*60*60); // write to the client's cache response. addCookie (nameCookie );}}}}

Browser:



Subsequent Refresh:

Cached file:



How does Servlet understand sessions?

Session is a persistent connection at the http level. It is implemented by adding a session recognition data each time an http packet is submitted, regardless of any means (such as Cookie, or adding additional content to the url like. net.

For example:
Client application link
The server creates a session and returns a session id.
The client submits this session id every time, and the server will think that this is the previously applied link.
The client does not submit data for a long time, or the application is disconnected. The server releases the session.

Servlet cookie and session

Cookie working principle.
Cookie is a piece of text sent by the server to customer service.
The server sets the set-Cookie response header and sends it to the client as a key-value pair. When the client requests again, the cookie is sent to the server as a request header. After the server receives the request, the two cookies are the same, so they are considered to be the same user.
Two Cookie methods: 1. The cookie exists in the Client Cache and disappears when the browser has disabled the Cookie.
2. It exists in the customer service file. You can set the expiration time to disappear as soon as the expiration time is reached.

How sessoin works.
The Session is sent as a cookie and is cached in the client browser. Therefore, when the session is closed, the session will disappear. At the same time, there is only one Session object for the same customer service.

1. the client sends a request and the server calls reques. getsession () generates a session object, and assigns a sessionid to the session object. It takes the session object as the value and sessionId as the key and stores it in a map set.
2. When the server responds, the session is sent to the client as a response header.
3. When the client sends a request again, the sessionid is sent to the server as the request header. The server finds the corresponding session object based on the sessionid of the response and tracks the session object.

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.