当前位置:网站首页>The principle of session and cookie
The principle of session and cookie
2022-06-29 09:25:00 【likeGhee】
List of articles
sketch
cookie and session It is a commonly used mechanism for recording status in development .
The same thing :
- Both of them can be used to keep private things , There is also a term of validity .
- cookie and session Are used to track the identity of the browser user's session .
Difference :
- cookie The data is saved on the client side ,session Data is saved on the server side .
- session It's on the server , Whether it expires or not depends on the server settings ,cookie There are clients , Expired or not in cookie Set it when generating , You can also clean it up by yourself .
- From a server perspective ,cookie Cannot query across browsers ,session You can query across browsers (sessionid Pass value )
Application :
cookie Is not very safe , Others can analyze the local COOKIE And carry on COOKIE cheating , If the main consideration is safety, we should use session
session It will be saved on the server for a certain period of time . When visits increase , It will take up the performance of your server , If the main consideration is to reduce server performance , Should be used COOKIE ;
So we can store the login information and other important information as seesion; If other information needs to be retained, it can be placed in cookie in .
cookie What is it? :
- cookie Is a text string handle sent to the client's browser , And save it on the client's hard disk , Can be used in some WEB Persistent hold data between site sessions .
session What is it?
- Session It's actually using Cookie Information processing , When the user first makes a request , The server creates a Cookie, When this Session At the end , In fact, it means this Cookie It's expired. .
cookie
How to create cookie
add to cookie
@WebServlet("/addCookie")
public class AddCookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("name", "likeghee");
resp.addCookie(cookie);
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write(" add to cookie success ");
}
}
Call the interface 
F12 Looking at the response header, you can see Set-Cookie
How to get cookie
@WebServlet("/getCookie")
public class GetCookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write(cookie.getName() + "--" +
cookie.getValue() + "|||||");
}
}
}
call getCookie Interface 
F12 see network, We can see that the client will send a message through the request header cookie Pass it to the server , So why can the server pass req.getCookies(); Get to the browser cookie
Google Chrome can click the exclamation point to view the local cookie What are they? 
cookie principle
establish cookie technological process :
- Client calls addCookie Interface
- The server uses the response header to cookie The information is returned to the client
- Client get server creation cookie Save information locally
obtain cookie technological process :
- Client calls getCookie Interface
- The client uses the request header to cookie Send information to the server
- The server can use req.getCookies(); obtain cookie Information
Each time a request is made, the browser will cookie Put the request header , The server gets... From the request header cookie Information
session
How to create session
@WebServlet("/addSession")
public class AddSessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// The default is true, obtain session, If session non-existent , Just create a new one
// obtain session, If session non-existent , Then return to null
HttpSession session = req.getSession(true);
session.setAttribute("name", "likeghee");
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write(" add to session success ");
}
}
After calling the interface , Let's go to see cookie
Current site cookie One more JSessionId
How to get session
@WebServlet("/getSession")
public class GetSessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// The default is true, obtain session, If session non-existent , Just create a new one
// obtain session, If session non-existent , Then return to null
HttpSession session = req.getSession(false);
String name = (String) session.getAttribute("name");
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write(name);
}
}
F12 Check the request header , The client will sessionID To the server 
session principle
add to session:
- Client calls add Interface , Server calls req.getSession(true); Server creation session
- The server sends... Through the response header sessionId Return to the client
obtain session:
- The client will be local sessionId Put it into the request header to call get Interface
- Server calls req.getSession(false); The server uses... In the request header sessionId To find the corresponding value
Leftovers
We can see sessionId The expiration time of is when the browser is closed , So the browser closes , The client calls again get Interface , The server will not be able to get... From the request header sessionId, You can't get the value .
Similarly, you can't find the result in another browser , because session Use , It's using cookie Principle
Why add getSession(true), And when the getSession(false)?
If we will get the false Change it to true, Client calls get Interface , If the request header does not sessionId, The server will create session, This is not what we want , establish session It should be add Interface is used
If the browser is disabled cookie, How to use session Well ?
sessionId Not through cookie Pass on , Using cache files , We use it ourselves GET/POST Form will sessionId Pass between server and client
session The value of is stored in jvm Medium , So restart the server ,session Values will be destroyed , The general practice is to cache values into redis among
colony session Sharing issues ?
How to solve the problem of invalid release version ?
边栏推荐
- 查找字符串中重复次数最多的元素
- Simplicity Studio无法识别新买的JLink v9解决方法
- Unity C # e-learning (12) -- protobuf generation protocol
- Which securities company is good for opening a mobile account? Is it safe to open an account online?
- MySQL uses union all to count the total number of combinations of multiple tables and the number of tables respectively
- 微信小程序项目:tab导航栏
- How to implement observer mode
- UE4 在4.20-23版本安装Datasmith插件
- MH/T 6040航空材料烟密度试验
- Laravel 8 enables the order table to be divided by month level
猜你喜欢

【目标检测】|指标 A probabilistic challenge for object detection

Find the most repeated element in the string

UE4 remove the mask transparent white edge in the material

AugFPN:改進多尺度特征學習用於目標檢測

Share code snippets of wechat applet

Handwritten virtualdom

How is epoll encapsulated in golang?

UE4 蓝图修改Array 中Get a copy 为 reference

Pytorch summary learning series - operation

SSD改進CFENet
随机推荐
Simplicity Studio无法识别新买的JLink v9解决方法
Debug H5 page -vconsole
Detecting and counting tiny faces
Network learning of pointnet
微信小程序搜索关键字高亮和ctrl+f搜索定位实现
Wechat applet search keyword highlighting and ctrl+f search positioning
pytorch总结—自动求梯度
How is epoll encapsulated in golang?
What is hyperfusion? What is the difference with traditional architecture
Can we trust bounding box annotations for object detection
Summary of IO streams
[target detection] | indicator a probabilistic challenge for object detection
手机开户一般哪个证券公司好?究竟网上开户是否安全么?
微信小程序自定义多项选择器
Which securities company is good for opening a mobile account? Is it safe to open an account online?
easyexecl导出100万行execl报字体错误的解决办法
Picture format -webp
AugFPN:改進多尺度特征學習用於目標檢測
Augfpn: improved multiscale feature learning for target detection
Detecting and counting tiny faces