Serlvet the session cookie and learning

HTTP protocol

Web communication requires a language, like Chinese people speak Chinese, English-speaking Europe, HTTP protocol used by Web, also known as hypertext protocol.

Chicken and duck .png

Using the HTTP protocol divides people into two categories: client and server. The role of the requested resource is the client, the server is providing the resources.

Communication .png

HTTP protocol is a very wonderful thing, he is only responsible to speak, as he did not know what to say. So HTTP is a stateless protocol.

Memory of the fish .png

Conversation

HTTP is stateless, but people have to remember is that people want something to remember HTTP, and then proposed several solutions:

  1. Hidden form fields
  2. Url rewrite
  3. cookie
  4. session

cookis Profile

A cookie is a small pieces of text information (micro redis database), about the size of 4kb, on the browser's memory or disk, you can set the survival time, the browser closes disappeared. Unless the disk is stored in.

cookies usage scenarios

  1. Remember username and password
  2. shopping cart
  3. Targeted advertising

Send cookies

  1. Creating cookies
  2. Sets the maximum age
  3. Cookie placed into the HTTP response header
Cookie c = new Cookie("userID", "a1234");
c.setMaxAge(60*60*24*7);
response.addCookie(c)
复制代码

Read Cookie

String cookieName = "userID";
Cookie[] cookies = request.getCookies();
if(cookies != null){
    for(Cookie cookie : cookies){
        if(cookieName.equals(cookie.getName())){
            doSomethingWith(cookie.getValue());
        }
    }
}
复制代码

session

Presence server memory text information (micro redis database)

Creating session

HttpSession session = request.getSession;
复制代码

HttpSession的API

pubic Object getAttribute(String name); //根据name 获取属性的值

public void setAttriute(String name, Object value); //设置一个名称和对应的值

public void logout() //将会话从客户端注销
复制代码

session usage scenarios

  1. shopping cart
  2. Verification code

cookie and session distinction

cookie session
Exist browser Presence server
Low safety factor Safer

reference:

<< servlet and jsp core programming >>

<< servlet and jsp study guides >>

<< graphical HTTP >>

Guess you like

Origin juejin.im/post/5dd62f90e51d453677066be5