Fundamentals of Java EE (04): session tracking technology, detailed explanation of session and cookie

1、 Session tracking

1. Scene description

For example, if you log in to a shopping website and your identity is recognized successfully, you can place an order and pay on the website. In these operations, the information of the current logged in user must be shared, so that these operation results can be associated with the logged in user.

2. Concept introduction

A session can be understood as an interaction between the client and the server, which may contain multiple requests and responses. In Java Web, the session starts from the first request from the client to the server until the client closes the browser and the session ends. Sharing data among multiple requests in a session is called session tracking technology.

2、 Detailed explanation of cookie usage

1. Cookie introduction

In HTTP, cookies are usually used to identify the user's identity and track the session. The data stored on the user's local terminal is generally encrypted and temporarily or permanently saved by the user's client computer. Its structure is composed of a key and a value. With the server-side response sent to the client browser. Then the client browser will save the cookie and send the cookie to the server the next time it accesses the server.

Cookies are key value pairs created by the server and sent to the client in response. The client will save the cookie and mark the source of the cookie. When the client sends a request to the server, it will include the cookie in the request and send it to the server, so that the server can recognize the client.

2. Cookie usage

In Java Web, you can create cookies based on servlets and set properties.

public class CookieServletOne extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,HttpServletResponse response)
            throws ServletException,IOException {
        response.setContentType("text/html;charset=utf-8");
        // 创建Cookie
        Cookie cookie = new Cookie("author","cicada");
        // 设置生命周期 1小时
        cookie.setMaxAge(60*60);
        response.addCookie(cookie) ;
        response.getWriter().print("Hello:Cookie");
    }
}

visit: http://localhost:6002/cookieServletOne

View response header:

Response Header
Set-Cookie: author=cicada; Max-Age=3600;

In this way, the cookie created by the server is obtained on the client.

public class CookieServletOne extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request,IOException {
        System.out.println("doPost...");
        Cookie[] cookies = request.getCookies() ;
        for (Cookie cookie:cookies){
            System.out.println("Name:"+cookie.getName());
            System.out.println("Value:"+cookie.getValue());
        }
        response.setContentType("text/html;charset=utf-8");
        String userName = request.getParameter("userName") ;
        response.getWriter().print("Hello:"+userName);
    }
}

After passing the test, the console outputs: Name: author; Value:cicada。

Update refers to the overwriting of cookies. If the server sends duplicate cookies, the original cookies will be overwritten.

public class CookieServletTwo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,"smile");
        // 设置生命周期 2小时
        cookie.setMaxAge(60*60*2);
        response.addCookie(cookie) ;
        response.getWriter().print("Hello:Cookie");
    }
}

You can test the result of cookie acquisition through the above method.

cookie. Setmaxage (0): life equal to 0 is a special value, which indicates that the cookie is invalidated.

public class CookieServletTwo extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request,IOException {
        response.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = request.getCookies() ;
        for (Cookie cookie:cookies){
            if (cookie.getName().equals("author")){
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
        String userName = request.getParameter("userName") ;
        response.getWriter().print("Hello:"+userName);
    }
}

In this way, the cookie acquisition method is tested again, and it is found that there are no cookies deleted above.

3. Cookie related API

Sets the time, in seconds, when cookies expire. By default, cookies will only be valid in the current session.

Gets the maximum lifetime of the cookie.

Gets the name of the cookie. The name cannot be changed after creation.

Gets the value associated with the cookie.

Set the value associated with the cookie. Multiple settings of the same name will be overwritten.

3、 Session tracking

1. Session Introduction

In session management, when a user jumps between web pages of an application, the variables stored in the session object will not be lost, but will continue to exist throughout the user session. The servlet can save the data to be shared in a session to the httsession object. Four domain objects: pagecontext, ServletRequest, httpsession and ServletContext.

2. Session operation principle

When using a session for the first time, the server side needs to create a session. The session is saved on the server side and the data is saved in the session. The sessionid is sent to the client through a cookie and exists only in the browser's current session. That is, if the user closes the browser, the cookie will be lost.

When the client accesses the server again, it will bring the sessionid in the request. The server will find the corresponding session through the sessionid without creating a new session.

When a session is not used for a long time, the server will delete the session. The duration is configured in Tomcat as 30 minutes, which can be found in ${Catalana} / conf / Web This configuration can also be found in the web. XML Overwrite this configuration in XML!

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

3. Related API usage

If the session object already exists in the current session, return directly. If the current session does not exist, create the session object and return.

Returns the object with the specified name in the session.

A string of unique identifiers assigned to the session.

Bind an object to the session with the specified name.

Remove the object with the specified name from the session.

4. Application case

In the website, a frequently visible function is the last login time. This function can be easily implemented based on session.

public class SessionServletOne extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,IOException {
        response.setContentType("text/html;charset=utf-8");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HttpSession session = request.getSession(true) ;
        Date createTime = new Date(session.getCreationTime());
        Date lastAccessTime = new Date(session.getLastAccessedTime());
        session.setAttribute("author","cicada");
        response.getWriter().print(
                "SessionId:" + session.getId() + "<br/>"+
                "User Author:" + session.getAttribute("author")+"<br/>"+
                "Create Time:" + dateFormat.format(createTime)+"<br/>"+
                "Last Access Time:"+dateFormat.format(lastAccessTime));
    }
}

visit http://localhost:6002/sessionServletOne

Page printing, multiple visits, view the effect.

SessionId:40C12C367CBFA7469D57E72C5C091300
User Author:cicada
Create Time:2019-12-14 15:34:10
Last Access Time:2019-12-14 15:35:13

4、 Source code address

GitHub·地址
https://github.com/cicadasmile/java-base-parent
GitEE·地址
https://gitee.com/cicadasmile/java-base-parent
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>