Home  >  Article  >  Java  >  How to use cookies and session technology in Java

How to use cookies and session technology in Java

王林
王林forward
2023-04-23 18:55:071203browse

    Solution to http stateless protocol:

    HTTP is a stateless protocol. Stateless protocols do not require the server to retain information or state about each user across multiple requests.

    But some web applications may have to track the user's progress from one page to another, for example, when the web server is required to customize web page content for the user. Solutions for these situations include:

    • #Use of HTTP cookies.

    • Server-side session.

    • Hidden variables (when the current page contains a form)

    • Use URL rewriting of URI-encoded parameters, for example, /index.php? session_id=some_unique_session_code.

    The reason for making the protocol stateless is that the server does not need to track the status of multiple requests, not that it cannot do so if it wants to. This simplifies the contract between client and server and in many cases (such as serving static data via a CDN) minimizes the amount of data that needs to be transferred. If the server is required to maintain state for client access, the structure for making and responding to requests will be more complex. In fact, the simplicity of the model is one of its greatest features.

    1. Cookie

    1. The concept of cookie

    Cookie is a session technology that is created and maintained on the server but saved on the browser side

    Cookie application scenarios: remember username and password, no need to log in for seven days

    2, cookie creation

    //创建cookie
    Cookie cookie = new Cookie("username", "admin");
    //将cookie响应到浏览器
    response.addCookie(cookie);

    How cookies are represented in messages:

    If in Create a cookie in the server and respond to the browser. At this time, the response message will appear: Set-Cookie: username=admin

    After that, every time the browser sends a request to the server, it will carry this cookie. Will appear in the request message: Cookie: username=admin

    After responding to the cookie to the browser, it will be stored in the browser's running memory. When the browser is closed, the browser's running memory will be Released, so the cookie will be cleared. Therefore, the default validity time of the session is from the time the browser is opened to the time it is closed.

    3. Get the cookie

    //获取浏览器发送请求所携带的所有cookie
    Cookie[] cookies = request.getCookies();
    if(cookies != null){
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() + "," + cookie.getValue());
        }
    }

    4. Modify the cookie

    a> Because cookies are in key-value format data, so you only need to create cookies with the same key and different values, and in response to the browser, the corresponding cookie value will be overwritten

    b>Use cookie.setValue()

    /*Cookie cookie = new Cookie("username", "root");
    response.addCookie(cookie);*/
    Cookie[] cookies = request.getCookies();
    if(cookies != null){
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("username")){
                cookie.setValue("zhangsan");
                response.addCookie(cookie);
            }
        }
    }

    5. Set the validity time of the cookie

    After the cookie is responded to the browser, it will be stored in the browser's running memory. When the browser is closed, the browser's running memory will be released, so the cookie will be cleared. Therefore, the default validity time of the session is from the time the browser is opened to the time the browser is closed.

    But you can set the validity time of the cookie through cookie.setMaxAge()

    a>When the set validity time is a negative integer , has no effect, that is, the valid time is from when the browser is opened to when the browser is closed

    b>When the set valid time is 0, it means that the cookie is deleted immediately

    c>When the set valid time is When the time is a positive integer

    If the valid time is less than one session, the cookie will be automatically deleted from the running memory when it reaches the specified time

    If the valid time is greater than one session, when the browser is closed, it will Save the data in the cookie to the disk. When the browser is opened again, the data in the disk will be reloaded into the running memory

    6. Set the effective path of the cookie

    cookie. setPath();

    When a cookie is created and responded to the browser, a cookie with a valid path is set, and the cookie will only be carried when accessing the specified path

    2. session

    1. The concept of session

    session is a session technology that is created and maintained in the server and saved on the server side

    Application scenarios of session: recording the user’s login status

    2. Observe the changes in the packets when obtaining the session

    Obtain the session object through request.getSession()

    When request.getSession( is accessed for the first time in this session ) when obtaining the session object, a cookie with the key JSESSIONID will appear in the response message

    Every time a request is sent to the server through the browser, the cookie with this JSESSIONID will be carried even if the server is accessed

    When, use request.getSession() to obtain the session object again. As long as there is a JSESSIONID cookie in the request message, this cookie will no longer appear in the response message

    3. The principle of session

    Question:

    What is the principle of session?

    What is the relationship between session and cookie?

    Why are the same sessions obtained in one session?

    Answer:

    When the session is obtained through request.getSession(), the cookie with the key JSESSIONID in the request message will be obtained

    If there is no key in the request message, The cookie of JSESSIONID indicates that the current session has just started and is the first time to obtain the session object in the current session. At this time, the session object will be created inside the server, and a cookie will be created with the key JSESSIONID and the value a random sequence of UUID; then the created session object will be stored in a map collection maintained by the server, with the UUID random sequence as the key. , using the session object as the value, and finally responding to the cookie of JSESSIONID to the browser

    若请求报文中存在键为JSESSIONID的cookie,此时获取该cookie的值,即UUID随机序列,以UUID随机序列为键,从服务器所维护的map集合中就可以获取唯一的session对象

    4、session的常用方法

    4.1、session存在域对象的数据

    void setAttribute(String name, Object value);

    Object getAttribute(String name);

    void removeAttribute(String name);

    4.2、设置session的时效

    session的时效指在指定时间内,若没有对session进行任何的操作,此时session会自动失效

    a>通过web.xml设置,单位是分钟

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

    b>通过session.setMaxInactiveInterval()设置,单位是秒

    session.setMaxInactiveInterval(1800);
    4.3、强制使session失效

    session.invalidate()

    5、session的钝化和活化

    session的钝化指服务器关闭,但是浏览器没有关闭,此时session中的数据会被序列化到磁盘上

    session的活化指服务器启动,并且浏览器仍然没有关闭,此时会将序列化到磁盘上的数据重新加载到内存中

    注意:若session中存储的是实体类对象,此时若要钝化,则该实体类和该实体类的成员变量也都要实现序列化的接口

    三、cookie和session的区别

    1、cookie存储在浏览器端,session存储在服务器端,因此cookie相对而言不安全

    2、cookie只能存储字符串类型的键值对,session可以存储任意类型的数据,因此若存储相同的数据,cookie可能会产生大量的cookie

    3、由于每次浏览器发送请求都会携带cookie,若有大量的cookie,就会造成网络负担

    The above is the detailed content of How to use cookies and session technology in Java. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete