当前位置:网站首页>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>
边栏推荐
- oracle 触发器实现级联更新
- Data flow diagram, data dictionary
- 杭电oj2092 整数解
- 一个简单LEGv8处理器的Verilog实现【四】【单周期实现基础知识及模块设计讲解】
- The difference between memory overflow and memory leak
- Substance Painter笔记:多显示器且多分辨率显示器时的设置
- SAKT方法部分介绍
- Laravel5 call to undefined function OpenSSL cipher IV length() error php7 failed to open OpenSSL extension
- Details of redis core data structure & new features of redis 6
- Environment configuration of lavarel env
猜你喜欢
Démontage de la fonction du système multi - Merchant Mall 01 - architecture du produit
数据流图,数据字典
Advanced Mathematics - Chapter 8 differential calculus of multivariate functions 1
一个简单LEGv8处理器的Verilog实现【四】【单周期实现基础知识及模块设计讲解】
Mrs offline data analysis: process OBS data through Flink job
MRS离线数据分析:通过Flink作业处理OBS数据
JS get the current time, month, day, year, and the uniapp location applet opens the map to select the location
最长上升子序列模型 AcWing 1014. 登山
Vmware共享主机的有线网络IP地址
Redis 核心数据结构 & Redis 6 新特性详
随机推荐
Leetcode——剑指 Offer 05. 替换空格
PERT图(工程网络图)
Environment configuration
call undefined function openssl_ cipher_ iv_ length
Introduction to sakt method
Navigation — 这么好用的导航框架你确定不来看看?
请问,我kafka 3个分区,flinksql 任务中 写了 join操作,,我怎么单独给join
Wired network IP address of VMware shared host
Analysis of arouter
UML state diagram
Cesium knows the longitude and latitude of one point and the distance to find the longitude and latitude of another point
常用數字信號編碼之反向不歸零碼碼、曼徹斯特編碼、差分曼徹斯特編碼
内部排序——插入排序
Excuse me, why is it that there are no consumption messages in redis and they are all piled up in redis? Cerely is used.
Redis 核心数据结构 & Redis 6 新特性详
Horizontal of libsgm_ path_ Interpretation of aggregation program
Cascading update with Oracle trigger
Search engine interface
CVPR2022 | 医学图像分析中基于频率注入的后门攻击
Excuse me, does PTS have a good plan for database pressure measurement?