当前位置:网站首页>Differences among cookies, session, localstorage and sessionstorage
Differences among cookies, session, localstorage and sessionstorage
2022-06-24 10:37:00 【Yansuizi blog】
Catalog
One 、 Some conceptual understanding
1、 conversation Cookie And persistent Cookie
2、Cookie It is not cross domain
Four 、Cookie and Session The difference between
5、 ... and 、localStorage( Keep forever )
6、 ... and 、sessionStorage( Temporary storage )
7、 ... and 、localStorage and sessionStorage Comparison of
8、 ... and 、 contrast Cookie,Web Storage The advantages of
Nine 、localStorage and sessionStorage An example of
Ten 、 The difference between browser local storage and server storage
One 、 Some conceptual understanding
- Cookie & Session( Session tracking technology )、H4 The storage mechanism of ;
- localstorage、Sessionstorage yes Web Storage,H5 Local storage mechanism . Is aimed at HTML4 in Cookie An improvement in the storage mechanism , because Cookie The storage mechanism has many disadvantages ,HTML5 Don't use it anymore , Turn to the improved Web Storage Storage mechanism .
3.WebStorage Two main goals :(1) Provide cookie Outside the path where session data is stored .(2) Provide a mechanism for persistent storage of large amounts of data across sessions .
4. conversation (session) track
conversation , It refers to a series of actions after users log on the website , For example, browse for items to add to the shopping cart and buy . conversation (Session) Tracking is Web Techniques commonly used in programs , Used to track the user's entire session . The common session tracking technology is Cookie And Session.Cookie Determine user identity by recording information on the client side ,Session Determine the user's identity by recording information on the server side .
Two 、Cookie
Cookie It's actually a short piece of text , Is a small piece of data that the server sends to the user's browser and stores locally .
The client requests the server , If the server needs to record the user status , Just use response Issue one to the client browser Cookie. The client will put Cookie Save up . When the browser makes another request to the same server , The browser links the requested url with the Cookie Submit to the server together . The server checks the Cookie, To identify user status .
Cookie To make based on stateless HTTP It is possible for protocols to record stable state information
1、 conversation Cookie And persistent Cookie
conversation Cookie: If you don't set the expiration time , It means this Cookie The lifetime of is during the browser session , Close the browser window ,Cookie Just disappear . This life cycle is browser session Cookie It's called conversation Cookie. conversation Cookie Generally, it is not stored on the hard disk, but in the memory .
persistent Cookie: If the expiration time is set , The browser will put Cookie Save to hard disk , Close and open the browser again , these Cookie Still valid until the expiration time is exceeded . Stored on the hard disk Cookie It can be shared between different processes in the browser .
2、Cookie It is not cross domain
That is to say , Browser access Baidu will not bring Google's Cookie;
3、Cookie Main role of
Session state management ( Such as user login status 、 Game score or other information to be recorded )
Personalization ( Such as user-defined settings 、 Theme, etc )
Browser behavior tracking ( Such as tracking and analyzing user behavior )
3、 ... and 、Session
Session It's another mechanism for recording customer status , The difference is Session Save on the server . When the client browser accesses the server , The server records client information in some form on the server . This is it. Session. When the browser accesses again, it only needs to start from the Session To find the status of the customer . When the client closes the session , perhaps Session End of session on timeout expiration . When the user establishes a connection with the server , The server will automatically assign a SessionId, To identify the unique identity of the user .
- When the server receives the request, it needs to create Session Object time , First, it checks whether the client request contains Sessionid.
- If there is Sessionid, The server will be based on the id Return the corresponding Session object ; If there is no Sessionid, The server will create a new Session object , And put Sessionid Return to the client in this response .
- Usually use Cookie Way to store Sessionid To client , In the interaction, the browser will Sessionid Send to the server .
- If user disabled Cookie, Use URL rewrite , Can pass response.encodeURL(url) To implement ; When the browser supports Cookie when ,url Do nothing ; When the browser doesn't support Cookie When , Will rewrite URL take SessionID After splicing to the access address .
Four 、Cookie and Session The difference between
① Save the way
Cookie Save in browser side ,Session Save on the server side ;
② Use mechanism
See II for details 、 Three points ;
③ Store content
Cookie Only string types can be saved , In the form of text ;
Session Through something like Hashtable Data structure to save , Can support any type of object (Session It can contain multiple objects );
④ The size of the storage
Single Cookie The saved data cannot exceed 4kb;
Session There is no limit to size .
⑤ Security
Cookie Existing attacks :Cookie cheating ,Cookie to intercept ;Session Is more secure than Cookie.
Why it's safe :
SessionID Stored in Cookie in , If we want to break through Session First of all, break through Cookie;
SessionID It's about someone logging in , Or start Session_start Just can have , So break through Cookie It's not necessarily possible to get SessionID;
The second start Session_start after , The last time SessionID It just doesn't work ,Session After expired ,SessionID And then it fails ;
SessionID It's encrypted. .
in summary , The attacker must break the encrypted SessionID, It's very hard. .
⑥ Application scenarios
Cookie:
Judge whether the user has logged in to the website , So that the next time you log in, you can automatically log in ( Or remember the code ). If we delete Cookie, Then each time you log in, you must fill in the relevant information of the login ;
Save the last login time and other information ;
Save last viewed page ;
Browse count ;
Session:
Shopping cart in online shopping mall ;
Save user login information ;
Put some data into Session in , For different pages of the same user ;
Prevent users from logging in illegally ;
⑦ shortcoming
Cookie:
Limited size ;
The user can operate ( Ban )Cookie, Limit functionality ;
Low security ;
Some states cannot be saved on the client side ;
Every time you visit, send Cookie To server , Waste bandwidth ;
Cookie Data has a path (path) The concept of , Can restrict Cookie Only belong to a certain path .
Session:
Session The more things you keep , The more server memory it takes up , For websites with more users online , Server memory pressure will be high ;
Depend on Cookie(SessionID Save in Cookie), If you disable Cookie, Use URL rewrite , unsafe ;
establish Session Variables have a lot of randomness , It can be called at any time , There's no need for developers to do precise processing , therefore , overuse Session Variables will make the code unreadable and hard to maintain .
⑧ On cross domain issues
Cookie Support cross domain access , For example domain Property is set to “.biaodianfu.com”, with “.biaodianfu.com” All domain names with suffix can access this Cookie. Cross domain Cookie Now it's widely used in the Internet , for example Google、Baidu、Sina etc. ;
Session Cross domain access is not supported .Session Only valid in his domain name .
⑨ About distinguishing paths
session It's impossible to distinguish paths , The same user is visiting a website , be-all session You can visit... Anywhere ;
and cookie If the path parameter is set , So the same website under different paths cookie We can't visit each other .
5、 ... and 、localStorage( Keep forever )
Save the data in the local hardware device of the client ( Usually referred to as a hard disk , It can also be other hardware devices ) in , Even if the browser is closed , The data still exists , The next time you open your browser to visit the website, you can still use .
6、 ... and 、sessionStorage( Temporary storage )
Save the data in session In the object . So-called session( conversation ), When a user is browsing a website , The time from entering the website to closing the browser , That is, the time users spend browsing this website .session Object can be used to save any data that is required to be saved during this period of time .
7、 ... and 、localStorage and sessionStorage Comparison of
① Life cycle
localStorage: The life cycle is permanent , After closing the page or browser localStorage The data in will not disappear .localStorage Unless you actively delete data , Otherwise the data will never disappear .
sessionStorage: The lifecycle is valid only in the current session .sessionStorage Introduced a “ Browser window ” The concept of ,sessionStorage Is the data that always exists in the same source window . As long as the browser window is not closed , Even if you refresh the page or go to another page of the same origin , The data still exists . however sessionStorage It will be destroyed when the browser window is closed . Open the same window and page independently at the same time ,sessionStorage It's different .
② Scope
sessionStorage Do not share in different browser windows , Can't share between different pages or tabs sessionStorage Information about .
localstorage It's shared in all the same source windows , Different pages of the same browser can share the same localStorage( The page belongs to the same domain name and port )
③ Storage location
localStorage and sessionStorage All saved on the client side , No interactive communication with the server .
④ Storage size
localStorage and sessionStorage The storage data size of is generally :5MB
⑤ Access method
localStorage:window.localStorage
sessionStorage:window.sessionStorage
⑥ Storage content type
localStorage and sessionStorage Only string types... Can be stored , For complex objects, you can use ECMAScript Provided JSON Object's stringify and parse To deal with it
⑦ Application scenarios
localStoragese: Often used for long-term login (+ Determine if the user has logged in ), Suitable for long-term storage of local data ;
sessionStorage: One time login of sensitive account ;
8、 ... and 、 contrast Cookie,Web Storage The advantages of
① More storage
cookie by 4KB, and Web Storage yes 5MB;
② Save network traffic
Web Storage Not delivered to server , Data stored locally can be obtained directly , It will not be like cookie Every request will be sent to the server , So it reduces the interaction between the client and the server , Save network traffic ;
③ For the kind of data that only needs to be saved when the user is browsing a group of pages and can be discarded after the browser is closed ,sessionStorage It will be very convenient ;
④ Quick display
Some data is stored in Web Storage On , Plus the browser's own cache . Getting data locally is much faster than getting it from the server , So it's faster ;
⑤ Security
Web Storage Not as HTTP header Send to server side , So security is relative to cookie It's higher , Don't worry about intercepting , But there is still the problem of forgery ;
⑥ WebStorage Provide more than cookie More convenient method of data operation
- setItem (key, value) —— Save the data , Store information in key value pairs .
- getItem (key) —— get data , Pass the key value in , You can get the corresponding value value .
- removeItem (key) —— Delete individual data , Remove the corresponding information according to the key value .
- clear () —— Delete all data
- key (index) —— Get the... Of an index key
Nine 、localStorage and sessionStorage An example of
<p id="msg"></p>
<input type="text" id="input" />
<input type="button" value=" Save the data " onclick="saveStorage('input');" />
<input type="button" value=" Reading data " onclick="loadStorage('msg');" />
//sessionStorage Example ( Save a session cycle : From open browser —— To close the browser window )
function saveStorage(id){
var target=document.getElementById(id);
var str=target.value;
sessionStorage.setItem("message",str);
// perhaps sessionStorage.message=str;
}
function loadStorage(id){
var target=document.getElementById(id);
var msg=sessionStorage.getItem("message");
// perhaps var msg=sessionStorage.message;
target.innerHTML=msg;
}
//localStorage Example ( It can be kept forever )
function saveStorage(id){
var target=document.getElementById(id);
var str=target.value;
localStorage.setItem("message",str);
// perhaps localStorage.message=str;
}
function loadStorage(id){
var target=document.getElementById("msg");
var msg=localStorage.getItem("message");
// perhaps var msg=localStorage.message;
target.innerHTML=msg;
}
Both of these methods are when the user is in input Type in the text box and click " Save the data " Button to save data , single click " Reading data " Button to read the saved data . But the two methods deal with the data differently , In the use of sessionStorage When the method is used , If the browser is closed , This data is lost , Next time you open the browser, click " Reading data " Button , No data can be read . In the use of localStorage When the method is used , Even if the browser is closed , The next time you open the browser, you can still read the saved data . however , Data is saved by different browsers , in other words , Opening another browser can't read the data saved in this browser .
Ten 、 The difference between browser local storage and server storage
The data can be stored locally in the browser , It can also be stored on the server side . Browsers can save some data , Direct local access when needed ,sessionStorage、localStorage and cookie All data stored locally by the browser . The server can also save all data of all users , But the browser needs to request data from the server when needed .
- The server can save the user's persistent data , For example, database and cloud storage store a large amount of data of users on the server side
- The server can also save the user's temporary session data , Server side session Mechanism , Such as jsp Of session object , The data is stored on the server ,
The server side stores all users' data , So the server side costs a lot ;
The browser side saves the data needed by different users in their respective browsers , The browser side is generally only used to store small data
边栏推荐
- 1. project environment construction
- [EI分享] 2022年第六届船舶,海洋与海事工程国际会议(NAOME 2022)
- Multithreaded applications - improve efficiency
- JMeter interface test tool foundation - badboy tool
- 5.菜品管理业务开发
- Web项目部署
- Flink集群搭建以及企业级yarn集群搭建
- Pycharm shortcut keys
- JMeter interface test tool foundation - use badboy to record JMeter script
- Resolved: methods with the same name as their class will not be constructors in
猜你喜欢
随机推荐
抓包工具charles实践分享
[JS reverse sharing] community information of a website
JMeter interface test tool foundation - badboy tool
线程调度的常用方法
Learn to use the phpstripslush function to remove backslashes
Flink cluster construction and enterprise level yarn cluster construction
Practice sharing of packet capturing tool Charles
JMeter接口测试工具基础— 取样器sampler(二)
283.移动零
用扫描的方法分发书稿校样
Appium automation test foundation - mobile end test environment construction (I)
【IEEE】自然语言处理与信息检索国际会议(ECNLPIR 2022)
Machine learning - principal component analysis (PCA)
顺丰科技智慧物流校园技术挑战赛(2022/06/19)【AK】
Cross domain overview, simple accumulation
线程池的执行流程
tf. contrib. layers. batch_ norm
程序员在技术之外,还要掌握一个技能——自我营销能力
leetCode-面试题 16.06: 最小差
Hill sorting graphic explanation + code implementation