[Summary] Session Technology Cookie&Session

  1. What is conversational technology?
    Answer: The behavior of one question and one answer between the server and the browser .

  2. Why conversational technology?
    Answer: Because the HTTP protocol is actually a stateless protocol . For the server, the server cannot distinguish whether each HTTP request comes from the same client or from different clients, because the HTTP request messages are all the same, and there is nothing in the message to indicate A piece of information about the identity of the client. Simply put, the server cannot distinguish between clients.
    However, we have such a demand: we hope that the server can help our client to store some data.
    All, the introduction of special conversation technology to solve the whole problem.

  3. What are the conversational techniques?
    Cookie and Session


Cookie

1. What is a cookie

A cookie is a small string of data. Data is made byServer generation, And then in the process of respondingPass to the client(Withset-Cookie response headerSent to the client in the form), the client saves it in time, and waits untilVisit the server next timeWhen (sent back to the server in the form of a Cookie request header), it willCarry this cookie. The server knows who is accessing it by parsing the request message.
A Cookie can be defined in the form of key-value pairs.
Cookie is an entity class. The construction method is:
Cookie(java.lang.String name, java.lang.String value)

Two, cookie application cases

Case 1: Display the user's last access time
@WebServlet("/last")
public class LastLoginServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        // cookie的值必须是字符串,并且里面不能有空格
        //获取cookie请求头  cookie:key=value;key=value
        //也就是对于获取cookie请求头的封装
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
    
    
            for (Cookie cookie : cookies) {
    
    
                if("lastLogin".equals(cookie.getName())){
    
    
                    String value = cookie.getValue();
                    long time = Long.parseLong(value);
                    Date date = new Date(time);
                    response.getWriter().println(date);
                }
            }
        }
        Cookie cookie = new Cookie("lastLogin", System.currentTimeMillis() + "");
        //这行代码其实就是对于设置Set-Cookie:key=value的封装
        response.addCookie(cookie);
    }
}
Case 2: Jump to a personal homepage after successful login
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        response.setContentType("text/html;charset=utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //不做任何校验,只要输入就当作登录成功
        Cookie cookie = new Cookie("username", username);
        response.addCookie(cookie);
        response.getWriter().println("登录成功,即将跳转至个人主页....");
        response.setHeader("refresh", "2;url=" + request.getContextPath() + "/info");
        //Context域不可以
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

    }
}
@WebServlet("/info")
public class InfoServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //
        String username = "";
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
    
    
            for (Cookie cookie : cookies) {
    
    
                if("username".equals(cookie.getName())){
    
    
                    username = cookie.getValue();
                }
            }
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println("<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>Title</title>\n" +
                "</head>\n" +
                "<body>");

        response.getWriter().println("欢迎您," + username);

        response.getWriter().println("</body>\n" +
                "</html>");
    }
}

3. Cookie settings

  1. Set time to live
cookie.setMaxAge(180);

by default, The parameter isnegative number, When the parameter is negative, the cookie is only stored in the browser memory,The cookie is invalid when the browser is closed.
If you want cookies to be able to proceedEndurance preservation, You need to set onepositive numberSurvival time, unit issecond.
If the parameter is set to0,thenDelete nowThe cookie.

  1. Set path
cookie.setPath(request.getContextPath() + "/info");

Significance of setting path: For example, setting a cookie is not required in some cases, such as requesting a static resource file, js, css file.
By default, if the path is not set, the cookie will be taken when accessing any resource under the current domain name. If you want to carry the cookie only part of the path, you can do so by setting the path.

Note : If the path is set in the cookie, directly setting MaxAge=0 can not delete the cookie immediately. Need at this timeWrite the code to set the path again

cookie.setMaxAge(0);
cookie.setPath(request.getContextPath() + "/info");
response.addCookie(cookie);
  1. Set domain name
cookie.setDomain("octavius.com");

If not set, the cookie defaults toCurrent domain nameThe next is valid, if it exceeds the current domain name, it is invalid.

You cannot set a cookie information that is not related to the current domain name

All subdomains can "inherit" the cookie of the parent domain

Fourth, the details are supplemented

  1. The name and value of the cookieAre all string types
  2. cookie it can only storeA small amountData, generally no more than 4k
  3. Different browsersbetweenNo cookies can be shared

Session

1. What is Session?

Server technology. When the client accesses the resources on the server, the server will open up a block for the browserMemory space, Different memory spaces and corresponding browsersBind one by one, If the browser wants to store the data in the future, it can be stored directly in the corresponding memory space.

2. How is session associated with the browser?

In fact, the underlying implementation of Session relies on cookies.

When the browser accesses the server, the server willGenerate a session object, The object has aUnique id, And then when responding, it will put the id of the session Through cookieReturn to the current client. After the client receives the cookie data
, it will be stored randomly; when next time you visit other sites on the server, it willBring the cookie back, The server canGet the id of the session, You can pass the session idGet the corresponding session object. Associate the current browser with the current session object.

Third, the creation of Session

request.getSession();
request.getSession(boolean create)

Difference:
Insert picture description here
So, how to judge whether the current request has a session object?
Determine whether the current request contains a valid cookie: JSESSIONID=xxxxxxxxxxxxx, if so, find the corresponding session object according to this id; ifNoWords, or aInvalid id, Then create a new session object for it at this time.

Four, Session function-Session domain

Operate the data in the Session through the following api

session.setAttribute();
session.getAttribute();
session.removeAttribute();

The difference between context domain, request domain, and session domain:

  • context domain: currentThere is only one in the app. Data can also be shared between different servlets.
  • request domain: only inWithin one requesteffective.
  • session domain: in the current applicationHow many browsers are there, There are as many sessions. The scope is also relatively wide. Data can also be shared between different servlets.

In actual application:

  • The session domain can be used to store user-related data, such as the user's username, user information, shopping cart, etc.
  • Context can be used to store data that has nothing to do with the user, such as the product classification of the current mall, digital, clothing, food

Five, the destruction of Session

  1. Will the session object be destroyed if I close the browser ?
    will not. At this time, the session object is similar to an unreachable state: when the browser is closed and then accessed with the browser, the server will give the browser a new JSESSIONID.
    But if it is not used for a period of time, it will be destroyed.

  2. Will the session object be destroyed if the server is closed ?
    meeting. Closing the server or uninstalling the application will destroy the session object.
    but,The data in the session will not be lost, Session id and data stored in the domainSerializationTo the local hard disk.
    Note: Do not verify this process by closing idea's tomcat and restarting it. Because the tomcat of idea deletes the configuration file every time before starting, and re-assigns the new tomcat configuration file, so you can't see this phenomenon.
    If you want to save persistently, you need to set maxAge:

@WebServlet("/session")
public class ServletSession extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        HttpSession session = request.getSession();
        //cookie的name必须为JSESSIONID
        //你创建的这个cookie和浏览器内部的cookie是两个cookie,只不过当你关闭浏览器的时候
        //浏览器内部的cookie就失效了,而你创建的cookie存活了下来
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(60 * 60);
        response.addCookie(cookie);
        session.setAttribute("name", "session");
        //获取JSESSIONID
        String id = session.getId();
        System.out.println(id);
    }
}

  1. How to actively destroy the data in the Session
    ①When the validity period is reached, the data in the session will be lost (30min) ②Actively
    call session.invalidate() to invalidate the entire session object
    ③session.removeAttribute, just remove one attribute

Guess you like

Origin blog.csdn.net/Octavius_/article/details/114503370