当前位置:网站首页>Cookie learning diary 1
Cookie learning diary 1
2022-07-05 04:24:00 【herb. dr】
Catalog
1.3 State management classification
2.5 Cookie Encoding and decoding
One 、 State management
1.1 Existing problems
HTTP Protocol is stateless , Can't save information submitted every time
If the user sends a new request , The server cannot know if it is connected to the last request .
For those that need to submit data multiple times to complete Web operation , For example, login , It's a problem .
1.2 Concept
Will browser and web Multiple interactions between servers are handled as a whole , And the data involved in multiple interactions ( I.e. status ) preserved .
1.3 State management classification
Client state management technology : Save state on client . The representative is Cookie technology .
Server state management technology : Save the state on the server side . The representative is session technology ( Server delivery sessionID When needed Cookie The way ) and application
Two 、Cookie Use
2.1 What is? Cookie
Cookie It's in the browser Web When a resource of the server , from Web The server HTTP The response header is accompanied by a small piece of data transmitted to the browser .
once Web The browser saved some Cookie, Then every time it visits the Web Server time , Should be in HTTP This is in the request header Cookie Send it back to Web The server .
One Cookie Mainly by the name that identifies the information (name) And the value (value) form .
2.2 establish Cookie
1、 establish
package com.ha.cookie;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieServlet extends HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1、 Server creation Cookie object
Cookie cookie = new Cookie("username", "HuAn");
// 2、 take Cookie Respond to clients
resp.addCookie(cookie);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
metadata-complete="true">
<servlet>
<servlet-name>ck</servlet-name>
<servlet-class>com.ha.servlet.CookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ck</servlet-name>
<url-pattern>/ck</url-pattern>
</servlet-mapping>
</web-app>
2、 see
Run and visit this page
(1) Check mode 1 :
There is a response in the response header cookie
(2) View mode 2
3、 Add
(1) Set the access path
(2) Set up the client cookie Valid time
(3) Set up multiple cookie
2.3 obtain Cookie
package com.ha.cookie;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLDecoder;
public class GetServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. adopt request Object to get all cookie
Cookie[] cookies = req.getCookies();
//2. Through the loop traversal Cookie
if(cookies!=null){
for(Cookie cookie : cookies){
System.out.println(URLDecoder.decode(cookie.getName(),"UTF-8") +":"+URLDecoder.decode(cookie.getValue(),"UTF-8"));
}
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
2.4 modify Cookie
Just make sure that Cookie If the name and path of the are consistent, you can modify
Cookie cookie = new Cookie("username", "Tom");
cookie.setPath("/myweb");
cookie.setMaxAge(60*60);
resp.addCookie(cookie);
Be careful : If you change cookie Of name And valid paths will be created cookie, And change cookie value 、 The validity period will cover the original cookie
2.5 Cookie Encoding and decoding
Cookie Chinese is not supported by default , Can only contain ASCI character , therefore Cookie Need to be right Unicode The characters are encoded , Otherwise, there will be confusion .
Coding can use java.net.URLEncoder Class encode(String str, String encoding) Method
Decode using java.net.URLDecoder Class decode(String str, String encoding) Method
2.6 Cookie pros and cons
1、 advantage :
Configurable expiration rules .
simplicity : Cookie Is a text-based lightweight structure , Contains simple key value pairs .
Data persistence : Cookie By default, it can be one before expiration - It has been stored on the client browser
2、 shortcoming :
Size Limited : Most browsers are right Cookie The size of 4K、8K word Section restrictions .
The user is configured to disable : Some users disable browser or client device reception Cookie The ability of , So it limits this function .
Potential security risks : Cookie May be tampered with . May pose a potential risk to security or lead to reliance on Cookie The application for failed .
边栏推荐
- Looking back on 2021, looking forward to 2022 | a year between CSDN and me
- kubernetes集群之调度系统
- 长度为n的入栈顺序的可能出栈顺序种数
- Threejs clicks the scene object to obtain object information, and threejs uses raycaster to pick up object information
- Threejs realizes sky box, panoramic scene, ground grass
- 【虚幻引擎UE】实现背景模糊下近景旋转操作物体的方法及踩坑记录
- 程序员应该怎么学数学
- Threejs loads the city obj model, loads the character gltf model, and tweetjs realizes the movement of characters according to the planned route
- How to carry out "small step reconstruction"?
- WGS84 coordinate system, web Mercator, gcj02 coordinate system, bd09 coordinate system - brief introduction to common coordinate systems
猜你喜欢
Aperçu en direct | Services de conteneurs ACK flexible Prediction Best Practices
自动语音识别(ASR)研究综述
Mxnet imports various libcudarts * so、 libcuda*. So not found
kubernetes集群之调度系统
[uniapp] system hot update implementation ideas
Moco is not suitable for target detection? MsrA proposes object level comparative learning target detection pre training method SOCO! Performance SOTA! (NeurIPS 2021)...
函數(易錯)
Rome链分析
揭秘技术 Leader 必备的七大清奇脑回路
The scale of computing power in China ranks second in the world: computing is leaping forward in Intelligent Computing
随机推荐
Web开发人员应该养成的10个编程习惯
PHP读取ini文件并修改内容写入
Un réveil de l'application B devrait être rapide
Interview related high-frequency algorithm test site 3
函數(易錯)
How to force activerecord to reload a class- How do I force ActiveRecord to reload a class?
TPG x AIDU | AI leading talent recruitment plan in progress!
Why do big companies such as Baidu and Alibaba prefer to spend 25K to recruit fresh students rather than raise wages by 5K to retain old employees?
How to realize real-time audio and video chat function
【虚幻引擎UE】实现背景模糊下近景旋转操作物体的方法及踩坑记录
[phantom engine UE] package error appears! Solutions to findpin errors
[phantom engine UE] the difference between running and starting, and the analysis of common problems
如何优雅的获取每个分组的前几条数据
Clickpaas low code platform
直播預告 | 容器服務 ACK 彈性預測最佳實踐
What is the reason why the webrtc protocol video cannot be played on the easycvr platform?
The scale of computing power in China ranks second in the world: computing is leaping forward in Intelligent Computing
[uniapp] system hot update implementation ideas
[finebi] the process of making custom maps using finebi
Function (error prone)