当前位置:网站首页>Do you really know session and cookies?
Do you really know session and cookies?
2022-07-27 05:46:00 【nuzzzzz】
Preface
We know ,HTTP It's a stateless agreement , The server does not know which user initiated the request . In some scenarios, we need to know which user initiated the request , Which user operates . For example, mall Services , The user initiates a request to place an order , The server needs to identify which specific user . So the server needs to use some mechanism to identify , Record user information , State, etc .
Session The mechanism can achieve , It allows stateless protocols to HTTP Stateful . The server creates its own... For each user who requests the server Session, Used to identify , Track this user .Session It's stored on the server , Can be stored in files , Memory , Data and so on , And it has a unique logo Session ID. Server creation Session after , Server through HTTP The protocol tells the client , In the local Cookie This is recorded in Session ID. In this way, every subsequent request from the same client will Cookie Send it to the server together , The server is stored in Cookie Of Session ID Find out the data stored in the server Session , You will know which user is requesting this time .

Session
Session The Chinese meaning is conversation , Prescription . In fact, it is a one-to-one interactive session state between the client and the server , It's an abstract concept . Many people think that Session It's the following code Session object , In fact, it's just a help Cookie It's just a general implementation of .Session There are many ways to achieve .
HttpSession session = request.getSession();Because most applications rely on Cookie To achieve Session track , That line of code above .Cookie It's real . The client requests the server and creates it for the first time Session When , Server through HTTP agreement (HTTP Of the response head Set-Cookie) Tell the client , Need to be local Cookie This is recorded in Session ID.key The value of is JSESSIONID.

In this way, every subsequent request from the same client will Cookie Send it to the server together , The server is stored in Cookie Of Session ID Find out the data stored in the server Session , You will know which user is requesting this time .
HttpSession session = request.getSession();But the client browser can be disabled Cookie Of , Then there will be problems in this way . But we can use URL Rewriting technology to achieve Session track , That is to say, all the request parameters of the request server are added with a user ID or Session ID that will do .
http://chenpi.com/list?sid=xxxWe said earlier Session Can be stored in files , Memory , Database and so on . Where the conversation information is stored depends on the business , All those who talk about technical architecture out of business scenarios are hooligans , Technology itself is not good or bad , It's just what business scenario is suitable for what technology , This is also one aspect of an architect's ability to consider technology selection .
however Session Mechanism needs to be considered in cluster service Session Consistency issues . You can do it in a cluster service Session Sync , But this method has some disadvantages , For example, synchronization is troublesome , Synchronization delay , Multiple computers store the same Session Waste storage space . Another common method is to use special Session Service cluster to save user session information , for example Redis Caching services , It can not only build cluster mode to realize high availability and expandability , And it's fast based on memory performance .
public UserContext getUserContext(HttpServletRequest request) { String userToken = getUserToken(request, COOKIE_KEY); if (!StringUtils.isEmpty(userToken)) { String userContextStr = redisUtils.getString(RedisKeyUtil.genKey(userToken)); if (!StringUtils.isEmpty(userContextStr)) { return JSON.parseObject(userContextStr, UserContext.class); } } return null;}public String getUserToken(HttpServletRequest request, String cookieName) { Cookie[] cookies = request.getCookies(); if (null != cookies) { for (Cookie cookie : cookies) { if (Objects.equals(cookie.getName(), cookieName)) { return cookie.getValue(); } } } return null;}Cookie
Cookie It's client technology , It's also the realization of many people Session The choice of conversation , The server can let the client write some information to the local Cookie in , To achieve the purpose of session tracking . But note that the browser is disabled locally Cookie The situation of .
Speaking of Cookie, I have to say that many advertisers , Websites and so on use our personal privacy for tracking , Analyze our behavior , Make personalized recommendation . Many websites use third parties Cookie Get user information , Send it to the server to record the user's behavior track . You must have met in other applications to discuss hair loss prevention , Then you open Taobao, surprised to find that you recommend a variety of anti hair loss shampoo . however , At present, some browsers have disabled the third party Cookie Or optimized , for example Safari,Mozilla etc. .
We can manually set some information to Cookie in , In this way, the client can not only use this information , In subsequent requests , The server can also do corresponding processing according to this information .
public void saveUserContext(HttpServletResponse response, String key, String value) { // Set up cookie Cookie cookie = new Cookie(key, value); cookie.setPath("/"); // Set a deadline , Negative numbers, for example -1 representative Web Delete when browser is closed , If you don't set it, the default is -1 cookie.setMaxAge(12 * 60 * 60); response.addCookie(cookie);}We can view the data stored locally through the browser Cookie Information , And other websites can scan and use our stored Cookie, So some secure or confidential information should not be stored in Cookie in , Because data security is relatively low . Under normal circumstances , More important information such as user login information is stored in the server Session in , Other information, such as conversations ID Can be stored in Cookie in .
And single Cookie There is also a limit to the size of , Different browsers have different restrictions , What's the average size Kb. Different browsers for a domain name under Cookie There is also a limit to the number of , Generally, there are dozens of them , There are also elimination strategies when the quantity is saturated , So we should pay attention to these situations , Try not to exceed the browser limit .
边栏推荐
- 刷脸支付用户主要优势是智能化程度高
- 记一次PG主从搭建及数据同步性能测试流程
- 建设创客教育运动中的完整体系
- Web3 traffic aggregation platform starfish OS interprets the "p2e" ecosystem of real business
- 怎样才能拿到期货开户最低的手续费?
- Seven enabling schemes of m-dao help Dao ecology move towards mode and standardization
- SeekTiger的Okaleido有大动作,生态通证STI会借此爆发?
- Common interview questions in software testing
- Which futures company has a low handling fee and a high refund?
- How to choose a good futures company for futures account opening?
猜你喜欢

怎么开立普通商品期货账户

SSTI 模板注入

解决MySQL JDBC数据批量插入慢的问题

kettle的文件名通配规则

如果面试官问你 JVM,额外回答“逃逸分析”技术会让你加分

Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output

Minimum handling charges and margins for futures companies

How does gamefi break the circle? Aquanee shows its style by real "p2e"

Basic layout of the page

You can't even do a simple function test well. What do you take to talk about salary increase with me?
随机推荐
Analyze the maker education DNA needed in the new era
2022/7/26 考试总结
「PHP基础知识」布尔型的使用
[网鼎杯 2020 青龙组]AreUSerialz(BUUCTF)
Sealem Finance-基于Web3的全新去中心化金融平台
Dimitra and ocean protocol interpret the secrets behind agricultural data
User page management
Think about the role of some documents
NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线
Fortex Fangda releases the electronic trading ecosystem to share and win-win with customers
手把手教你搭建钉钉预警机器人
jenkins构建镜像自动化部署
[MRCTF2020]PYWebsite 1
kettle如何处理文本数据传输为‘‘而不是null
CAP原则
MOVE PROTOCOL推出测试版,更可“0撸”参与P2E
The written test questions of 25 large Internet companies are summarized, and I have encountered packages.
[NPUCTF2020]ReadlezPHP 1
DeFi 2.0的LaaS协议Elephant,或许是你熊市下为数不多的获利手段
Minio分片上传解除分片大小限制 - chunk size must be greater than 5242880