Java Web-Cookie和Session

Java Web-Cookie和Session

Conversation

The concept of session

A browser session is established for the first time the browser sends a request to the server from a process wherein one disconnected session termination. It contains the multiple requests and responses.

A session is used between multiple requests a session in the range of shared data

Session is divided into two categories: client session technology (cookie) technology and server-side session (session).

cookie stored locally in the browser, a session every request carries it

Getting Started

step:

  1. Server creates a cookie object data binding

    new Cookie(String name,String value)

  2. Send object to the browser cookie

    response.addCookie(Cookie cookie)

  3. The browser returns the cookie obtain, to get data

    Cookies[] request.getCookies()

Code:

cookieDemo1.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
        cookie快速入门
         */
        //1.创建cookie对象
        Cookie c=new Cookie("msg","hello");
        //2.通过添加到response从而发送cookie给客户端
        response.addCookie(c);
    }

cookieDemo2.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
        cookie快速入门
         */
        //3.获取cookie
        Cookie[] cookies = request.getCookies();
        //4.遍历cookies,获取数据
        if(cookies!=null){
            for (Cookie c:cookies
                 ) {
                String name = c.getName();
                String value = c.getValue();
                System.out.println(name+":"+value);
            }
        }
    }

Note that if the access demo1 and demo2 are using two different browsers, is actually two sessions, the received cookie is empty

Principle Analysis

transmitting the cookie header in the response, transmitted in the form of key-value:set-cookie:msg-hello

After the browser receives the response data stored in the header to the browser ( which is why change the browser can not be used ), when a request is sent at the head of the cookie in the request sent to the server: cookie:msg=hello.

In fact, these dirty work are done browser and server software, the programmer just directly call a good package of API

There are a few key points:

  1. One can send multiple cookie: cookie can create multiple objects, use multiple calls addCookie response method to send cookie

  2. By default , cookie is stored in memory. When the browser is closed, cookie data is destroyed

    However, cookie can also be set to achieve persistent storage, which is by invoking the cookie method setMaxAge (int seconds), ie the lifetime of the cookie settings to achieve:

    • Set the positive: the cookie data is written to the hard disk file, the persistent storage, the incoming parameter indicates the cookie survival time
    • Negative: Default
    • Zero: a special case , means to delete cookie information (because the server can not operate the client's file, can only give instruction in this way)
  3. Before tomcat8, cookie data can not be stored directly in Chinese . In Version 8 or later to support, there will not be garbled. If it is 8 previous version, you need to be transcoded Chinese data , generally use URL encoding (that is, get Chinese way transmission parameters when used)

  4. A cookie is there capture range of : Suppose deployed multiple projects in a tomcat web server, then the cookie between projects default can not be shared. But also can be set: setPath (String path), set a cookie acquisition range, path defaults to the current virtual directory (/ xxx), but if set to /, which is the root path of the server, get on can be the same server in project sharing among the cookie

    But how to achieve shared across servers it? This requires another cookie method setDomain (String path), and if you set a domain name identical, then the cookie can be shared among multiple servers, such as: setDomain(".baidu.com"), as long as a domain name is the baidu.com can share

  5. cookie store data on the client browser, compared to the stored on the server, the security will be much lower, and very easy to lose

  6. There browser cookie limits for a single size (generally about 4KB, because the intention is to store the cookie data is small), and for limited (typically limited to less than 20) with the total number in a domain cookie. Of course, we can also be set in the client:

    We can also be saved to a browser cookie management (shown here is the persistent storage, which is stored in the hard disk):

  7. Since 5 and 6, the cookie is generally used to store a small amount, less sensitive and important data. the role of the cookie is without login to complete the identification server to the client , in order to achieve some personalized settings and lasting effect in force without login. Of course, if after logged in, you can record the user's settings on the server side, you do not need to use this method the cookie.

Session

concept

session server-side session techniques, in a session sharing data between multiple requests of the data stored in the object server.

Session and cookie, are domain objects

Getting Started

获取HttpSession对象:HttpSession session=request.getSession();

  1. Object getAttribute(String name)
  2. void setAttribute(String name,Object value)
  3. void removeAttribute(String name)

Sample code:

SessionDemo1.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //使用session共享数据
        //1.获取session
        HttpSession session = request.getSession();
        //2.存储数据
        session.setAttribute("msg","hello session");
    }

SessionDemo2.java

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //使用session共享数据
        //1.获取session
        HttpSession session = request.getSession();
        //2.获取数据
        Object msg = session.getAttribute("msg");
        System.out.println(msg);
    }

Similarly, after changed the browser is different from the two sessions, the data can not be shared

Principle Analysis

  1. How to ensure the server in a session scope, session objects multiple acquisitions is the same one?

    Session is dependent on the cookie! When you first get session, there is no corresponding cookie, this time will be created in memory a session object and returns an id, and by set-session:JSESSIONID=idsaved in a cookie in the browser of this session id is concerned, after the request, the server can be read in the session id cookie, you know the session corresponding session is which. This also explains why the session is stored on the server, but still only valid during a single session

  2. Client closes around, get twice the default session is not the same (because it is not a conversation of, cookie changed), but can be saved by the persistence still get the same session cookie realize after you close your browser

  3. In theory, the client does not shut down after the server is down, get twice the session is not the same. Because the session is saved on the server memory rather than on disk book

    But this will also cause problems: will result in the loss of user data, degrade the user experience. How to solve this problem?

    The solution is to use a sequence of session - the deserialization :

    First, Java serialization, you can see my this blog

    • Prior to shut down the server properly, we will be saved to the hard disk after the session object serialization. After serialization session file will be saved in the work directory
    • After the server is started, we set up server files automatically after the session of the hard disk serialized into session object in memory

    This is the principle level, but this part has been achieved tomcat: Now we use tomcat server, the default is realized serialization - deserialization function.

    However, the use of IDEA directly start the server, then deploy the project can not achieve this function. The reason is in the closed IDEA - will perform an operation tomcat server starts: the work directory delete and recreate, which makes the session file is saved in the work directory when the server is shut destroyed. It also illustrates the IDEA sense only for development projects, real or direct deployment project started when tomcat Haoshi to the production server.

  4. session when it will be destroyed?

    session would be destroyed in three ways:

    1. The server shuts down

    2. session object calls invalidate () method to make their failure

    3. session default expiration time is 30 minutes.

      This time is configurable. We can find the configuration as shown in tomcat's conf / web.xml, modify time here will be able to modify the default expiration time.

      At the same time, each project can also be set individually in their own web.xml, to set the project here will override the default settings for tomcat

  5. Only different memory strings and cookie, session storage object type is not required, the size of the object is also not required.

    Ye Hao understand this: cookie to be transmitted during each visit, so the size must be strictly controlled. The session has been saved on the server side does not move, so the size it appears important. But also because the same reason, the session data is safe, and it seems relatively insecure cookie

  6. Compared to us in this blog ServletContext introduction, we more often use the session and cookie to store a data session because its scope is more appropriate, less risk

Guess you like

Origin www.cnblogs.com/jiading/p/12013650.html