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.
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.
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.
Conversation
HTTP is stateless, but people have to remember is that people want something to remember HTTP, and then proposed several solutions:
- Hidden form fields
- Url rewrite
- cookie
- 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
- Remember username and password
- shopping cart
- Targeted advertising
Send cookies
- Creating cookies
- Sets the maximum age
- 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
- shopping cart
- 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 >>