当前位置:网站首页>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>
边栏推荐
- Million data document access of course design
- ARM Cortex-A9,MCIMX6U7CVM08AD 处理器应用
- Laravel5 call to undefined function OpenSSL cipher IV length() error php7 failed to open OpenSSL extension
- [network security] SQL injection syntax summary
- OAuth 2.0 + JWT protect API security
- 杭电oj2092 整数解
- Parameter keywords final, flags, internal, mapping keywords internal
- 搜索框效果的实现【每日一题】
- 云上“视界” 创新无限 | 2022阿里云直播峰会正式上线
- Démontage de la fonction du système multi - Merchant Mall 01 - architecture du produit
猜你喜欢
内部排序——插入排序
js 获取当前时间 年月日,uniapp定位 小程序打开地图选择地点
GAN发明者Ian Goodfellow正式加入DeepMind,任Research Scientist
手把手教会:XML建模
Substance Painter笔记:多显示器且多分辨率显示器时的设置
Navigation — 这么好用的导航框架你确定不来看看?
UML state diagram
Use case diagram
Codes de non - retour à zéro inversés, codes Manchester et codes Manchester différentiels couramment utilisés pour le codage des signaux numériques
PERT图(工程网络图)
随机推荐
FCOS3D label assignment
Flask session forged hctf admin
Oracle Linux 9.0 officially released
IP address home location query
Oracle Linux 9.0 正式发布
一个简单LEGv8处理器的Verilog实现【四】【单周期实现基础知识及模块设计讲解】
NDK beginner's study (1)
NLLB-200:Meta开源新模型,可互译200种语言
Details of redis core data structure & new features of redis 6
Excuse me, as shown in the figure, the python cloud function prompt uses the pymysql module. What's the matter?
Selenium库
请问,redis没有消费消息,都在redis里堆着是怎么回事?用的是cerely 。
Regular expression integer positive integer some basic expressions
最长上升子序列模型 AcWing 482. 合唱队形
Laravel5 call to undefined function OpenSSL cipher IV length() error php7 failed to open OpenSSL extension
bashrc与profile
Data flow diagram, data dictionary
【AI实战】应用xgboost.XGBRegressor搭建空气质量预测模型(二)
Reverse non return to zero code, Manchester code and differential Manchester code of common digital signal coding
When FC connects to the database, do you have to use a custom domain name to access it outside?