当前位置:网站首页>Differences between cookies and sessions
Differences between cookies and sessions
2022-07-07 14:23:00 【Bieyunchao】
Cookie and Session The definition of
- Cookie, Sometimes in the plural Cookies. The type is “ Small text files ”, It's some websites to identify users , Conduct Session Track and Stored in the user's local terminal The data on the ( Usually encrypted ), By the user client Information temporarily or permanently stored by a computer .
- Session: In the computer , Especially in network applications , be called “ Session control ”.Session Object stores the properties and configuration information required for a specific user session . such , When the user is in the Web When you jump between pages , Stored in Session The variables in the object will not be lost , But it's going on throughout the user session . When a user requests... From an application Web When the page , If the user does not have a session , be Web The server will automatically create One Session object . When the session expires or is abandoned , The server will terminate the session .Session One of the most common uses of objects is to store user preferences .
Cookie and Session The difference between
- Cookie It can be stored in the browser or locally ,Session Only servers exist
- session Able to store arbitrary java object ,cookie Can only store String Object of type
- Session Than Cookie More secure (Cookie There are security risks , Find your... By blocking or local files cookie Then we can attack )
- Session Take up server performance ,Session Too much , Increase server pressure
- Single Cookie The saved data cannot exceed 4K, Many browsers limit a site to save at most 20 individual Cookie,Session There is no size limit related to the memory size of the server .
Cookie Use
- Cookie Common methods in class
public void setMaxAge(int expiry)
public String getName()
public String getValue()
public void setValue(String newValue)
- The following is a classic case showing the last login time of the user
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Set response text information
resp.setContentType("text/html;charset=utf-8");
// Deal with the garbled code of requests and responses
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
// from request Get all Cookie
Cookie[] cookies = req.getCookies();
boolean flag = false;
// Traverse cookies
for (Cookie cookie : cookies) {
if (cookie.getName().equals("datetime")){
Date date = new Date(Long.valueOf(cookie.getValue()));
resp.getWriter().println(" Your last login time is :" + date.toLocaleString());
flag = true;
break;
}
}
if (!flag){
resp.getWriter().println(" This is your first login ");
}
long currentTimeMillis = System.currentTimeMillis();
// Respond to cookie
Cookie cookie = new Cookie("datetime", String.valueOf(currentTimeMillis));
resp.addCookie(cookie);
}
}
- Cookie How to deal with Chinese garbled code
// Here I am through the Chinese data URL The operation of encoding and decoding
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals("name")){
resp.getWriter().println(URLDecoder.decode(cookie.getValue(), "utf-8"));
System.out.println(URLDecoder.decode(cookie.getValue(), "utf-8"));
}
}
Cookie cookie = new Cookie("name", URLEncoder.encode(" Zhang San ","utf-8"));
resp.addCookie(cookie);
}
Session Use
- HttpSession The method commonly used in
public String getId();
public ServletContext getServletContext();
public Object getAttribute(String name);
public void setAttribute(String name, Object value);
public void removeAttribute(String name);
public void invalidate();
public boolean isNew();
- Session Medium storage data
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// obtain Session
HttpSession session = request.getSession();
// Store information
session.setAttribute("person", new Person(111," Zhang San "));
String id = session.getId();
if (session.isNew()){
response.getWriter().write(" The newly created session id=" + id);
} else {
response.getWriter().println("session It already exists id=" + id);
}
}
- Delete Session Two ways
- Delete manually
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
// Manual logout session
session.invalidate();
}
- adopt web.xml To achieve scheduled deletion
<session-config>
<!-- Set up session The expiration time of , In minutes -->
<session-timeout>1</session-timeout>
</session-config>
边栏推荐
- requires php ~7.1 -&gt; your PHP version (7.0.18) does not satisfy that requirement
- Search engine interface
- The meaning of variables starting with underscores in PHP
- IP and long integer interchange
- Bashrc and profile
- When FC connects to the database, do you have to use a custom domain name to access it outside?
- 一个简单LEGv8处理器的Verilog实现【四】【单周期实现基础知识及模块设计讲解】
- How to check the ram and ROM usage of MCU through Keil
- Laravel5 call to undefined function OpenSSL cipher IV length() error php7 failed to open OpenSSL extension
- First choice for stock account opening, lowest Commission for stock trading account opening, is online account opening safe
猜你喜欢

OAuth 2.0 + JWT 保护API安全

Use day JS let time (displayed as minutes, hours, days, months, and so on)

最长上升子序列模型 AcWing 1014. 登山

Substance Painter笔记:多显示器且多分辨率显示器时的设置

最长上升子序列模型 AcWing 482. 合唱队形

内部排序——插入排序

多商戶商城系統功能拆解01講-產品架構

LeetCode每日一题(636. Exclusive Time of Functions)

How to check the ram and ROM usage of MCU through Keil

STM32CubeMX,68套组件,遵循10条开源协议
随机推荐
Assign a dynamic value to the background color of DataGrid through ivalueconverter
请问,我kafka 3个分区,flinksql 任务中 写了 join操作,,我怎么单独给join
【立体匹配论文阅读】【三】INTS
Flask session forged hctf admin
The longest ascending subsequence model acwing 482 Chorus formation
When FC connects to the database, do you have to use a custom domain name to access it outside?
Leetcode——344. Reverse string /541 Invert string ii/151 Reverse the word / Sword finger in the string offer 58 - ii Rotate string left
【AI实战】应用xgboost.XGBRegressor搭建空气质量预测模型(二)
[AI practice] Application xgboost Xgbregressor builds air quality prediction model (II)
Environment configuration of lavarel env
Is it safe to open an account online now? Which securities company should I choose to open an account online?
How does MySQL control the number of replace?
MLGO:Google AI发布工业级编译器优化机器学习框架
LeetCode 648. Word replacement
请问指南针股票软件可靠吗?交易股票安全吗?
Navigation — 这么好用的导航框架你确定不来看看?
docker部署oracle
Common response status codes
Vscode configuration uses pylint syntax checker
Hangdian oj2054 a = = B? ???