Java Cookie and Session

Source: Internet
Author: User

Java Cookie and Session
1. Session technology Overview

The http protocol is stateless. Therefore, when the server receives an http request from the client, it cannot identify the client that the request comes from. Stateless protocols have advantages and disadvantages, but for businesses that need to identify the client or even remember the client, the http protocol should be "stateful ".

Remember that there are many types of client services. For example, log on to the system. After logging on to a page, you must also log on to the new website page. For example, in the shopping cart system, a user must ensure that item 2 can be added after item 1 is added, and all items in the shopping cart can be read during settlement.

How can the server remember the client? Currently, the most common session technologies are cookie and session.

  • 1. Cookie: data is stored locally on the client, which reduces the Storage pressure on the server and is not secure. The client can clear cookies.
  • 2. Session: data is stored on the server, which is relatively secure and increases the pressure on the server.
2. Cookie technology

Cookie technology is used to store user data to the client. It is used to enable the server to distinguish different clients based on the cookies held by each client.

Cookie is composed of cookie name, unique cookie value, and some attributes (path, expires, domain, etc.). value is the unique basis for distinguishing clients.

Cookie principle: After the server receives the first request sent by the client, the server adds the "set-cookie" field to the response header to send the request to the client. After the client receives the response, store cookie Information in the memory (if the MaxAge attribute is set, it is stored in the disk). Because cookie data is stored in the browser memory, no matter which page, when the client sends a request to the server again, it can obtain the cookie information and add the "cookie" field in the request header to the server. Then, the server can identify the client, and find the client information from the cookie.

Two problems to be solved when using cookies:

  • (1) How does the server send a Cookie to the client.
  • (2) How does the server accept cookies carried by the client.
2.1 The server sends a Cookie to the client

Several common methods for setting cookies are as follows:

  • Cookie(String cookie_name,String cookie_value): Construct a Cookie object.
  • setPath(uri): The cookie takes effect when accessing the path (including the sub-path) under the uri. For examplesetPath("/Cookie")When the local machine is usedhttp://localhost/Cookie/servlet1Andhttp://localhost/Cookie/servlet2This Cookie exists during access.
  • setMaxAge(int second): When this attribute is set, the cookie will be permanently saved to the client disk and saved for seconds. If the cookie does not have this attribute, the cookie will only be stored in the memory.
  • setDomain(String domain): Set the domain range in which the Cookie takes effect, for examplecookie.setDomain(".foo.com");This will take effect for all hosts in the foo.com domain (such as www.foo.com), but does not include subdomains (www.abc.foo.com ).

After setting the Cookie, you need to use the response method.addCookie(Cookie cookie)Add the cookie to the response header and send it to the client.

For example, the following is a servlet named CooikeDemo project. The uri path of this servlet is "/cookieservlet ".

Import java. io. IOException; import javax. servlet. servletException; import javax. servlet. http. cookie; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class CookieServlet extends HttpServlet {private static final long serialVersionUID = 1L; protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {Cookie cookie = new Cookie ("username", "zhangsan"); // construct the cookie object cookie. setPath ("/CookieDemo"); // set the cookie's valid uri range cookie. setMaxAge (10*60); // set the cookie to last to the disk for 10 minutes. addCookie (cookie); // Add the set-cookie field to the response header and send it to the client.} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}

The cookie is sent to the client by adding the set-cookie field in the Response Header:

When the client requests again, the cookie field is added to the request header.

Notes:

  • (1). Chinese characters cannot be stored in cookies.
  • (2) If no persistence time is set, the cookie will be stored in the browser's memory. When the browser closes, the cookie information will be destroyed, which is a session-level cookie. If the persistence time is set, the cookie information will be persisted to the disk, which is a persistent cookie. The persistence cookie does not expire as the browser closes, but is valid within the validity period.
  • (3 ).setPath()When the effective path is set to a directory, the cookie takes effect for the Directory and the resources in the subdirectory. If the effective path is a file, the cookie is only valid for the file. For example:
    Cookie. setPath ("/webapp"); // indicates that cookiecookie is carried when any resources in the webapp are accessed. setPath ("/webapp/cookieservlet"); // indicates that cookie information is carried only when cookieservlet in webapp is accessed.
  • (4) If you want to delete the currently valid cookie information, you can overwrite it with a cookie with the same path persistence time of 0. In this way, each time the client receives a response, the cookie becomes invalid immediately, and therefore it cannot carry the cookie to the server. For example, delete the cookie information in the preceding example.
    Cookie cookie = new Cookie("username","zhangsan");cookie.setPath("/CookieDemo");cookie.setMaxAge(0);response.addCookie(cookie);
2.2 The Server accepts cookies carried by the client

As shown in the preceding figure, the client's cookie information is sent to the server in the request header. Therefore, to obtain cookie information, the server must use the method in the request object.getCookies(). In this case, the only way to obtain the cookie is to return a set of Cookie arrays. Therefore, you need to traverse the array to obtain the cookie with the specified name.

For example, obtain a cookie Whose cookie name is "username.

Cookie[] cookies = request.getCookies();if(cookies != null) {    for (Cookie coo : cookies) {        String cookie_name = coo.getName();        if (cookie_name.equals("username")) {            String cookie_value = coo.getValue();            System.out.println(cookie_name+":"+cookie_value);        }    }}
3. Session Technology

The entire process from opening a browser to accessing a site, to closing the browser (releasing the browser memory) becomes a session. In addition to the Cookie technology, the server can remember the client during a Session, and the Session technology can also achieve this purpose.

Session technology stores data on the server. It creates a memory space for each client to store client data and assigns a JSESSIONID stored in the cookie to the client, the client needs to carry this ID each time, and the server can find the memory space of the client through this ID. Because this ID uses the unique id jsessionid of Cookie storage, Session is implemented based on cookies.

Session principle: After the server receives a request sent by a client for the first time, it generates a session and allocates a buffer for the session, at the same time, add the JSESSIONID pair of the session as the cookie name to the response header and return it to the client. The next time the client accesses the session, the request header will carry the JSESSIONID, the server searches for the matched session based on the jsessionid. If the corresponding session can be found, the server operates the session resource directly. Otherwise, a session and the corresponding buffer will be allocated for the JSESSIONID again.

To use Session technology, you need to solve the following three problems:

  • (1). How to obtain the session object (memory region) of a client )?
  • (2). How to access data in the session?
  • (3). What is the lifecycle of the session object?
3.1 obtain the Session object

The server uses the JSESSIONID in the cookie sent by the client to differentiate the client. You can obtain the session information related to the client through the information in the request packet.

HttpSession session = request.getSession();

This method has two functions:

  • (1). Obtain the JSESSIONID from the cookie and find whether the session object corresponding to the ID exists. If yes, the session object is obtained.
  • (2) If the client does not send the JSESSIONID or the JSESSIONID does not match the ID value of the server record, a session object is re-allocated for the JSESSIONID.

In fact, it is based on the JSESSIONID to determine whether the client already has a session on the server. If yes, It is used. If no session exists, it is allocated.

3.2 access data to the session (the session is also a domain object)

Session is also a domain object. The range of the session domain is the entire session, which can take effect for multiple requests from the client. This range is smaller than the context domain (application domain) and greater than the request domain (only valid in one request ).

As a domain object, the session object also has the following three methods:

session.setAttribute(String name,Object obj);session.getAttribute(String name);session.removeAttribute(String name);

In addition, you can usegetId()Method to obtain the JSESSIONID value of the session.

3.3 Session Object Lifecycle
  • Create: It is created when request. getSession () is executed for the first time.
  • Destruction:
    • 1. When the server (abnormal) is disabled.
    • 2. The session expires/expires (30 minutes by default, which can be modified in web. xml ).
      <session-config>  <session-timeout>30</session-timeout></session-config>
      Note the starting point of the expiration time, that is, when to start calculating 30 minutes? Start timing from never operating the server resources (that is, starting from the last time the session data is read ).
    • 3. Manually destroy the session:session.invalidate();.

That is to say, the client shares a session object for any resource in a session.

Q: When the browser is closed, will the session be destroyed?
No. The session is stored on the server and has little to do with the client. As long as the client does not operate on the session, the session will be automatically destroyed after a period of time.
However, after the browser is closed, the JSESSIONID in the cookie is lost, and the corresponding session data cannot be found. Jsessionid can be used as the cookie Attribute before sending the session to the client and the cookie persistence time can be configured to the client disk, so that jsessionid will not be lost when the browser is opened again. The code is roughly as follows:

HttpSession session = request. getSession (); session. setAttribute ("username", "Tom"); String id = session. getId (); // get the JSESSIONID value Cookie cookie = new Cookie ("JSESSIONID", id); // "JSESSIONID" is a fixed cookie. setPath ("/CookieDemo"); cookie. setMaxAge (12*60*60); // The JSESSIONID is persistently stored for 12 hours. addCookie (cookie); response. getWriter (). write ("JSESSIONID:" + id); System. out. println (session. getAttribute ("username "));

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.