当前位置:网站首页>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>
边栏推荐
- Similarities and differences between switches and routers
- bashrc与profile
- Million data document access of course design
- 杭电oj2054 A == B ? ???
- GVIM [III] [u vimrc configuration]
- requires php ~7.1 -&gt; your PHP version (7.0.18) does not satisfy that requirement
- requires php ~7.1 -&gt; your PHP version (7.0.18) does not satisfy that requirement
- Leetcode——剑指 Offer 05. 替换空格
- The difference between memory overflow and memory leak
- 最长上升子序列模型 AcWing 1012. 友好城市
猜你喜欢
Advanced Mathematics - Chapter 8 differential calculus of multivariate functions 1
AI talent cultivation new ideas, this live broadcast has what you care about
Reverse non return to zero code, Manchester code and differential Manchester code of common digital signal coding
Substance Painter笔记:多显示器且多分辨率显示器时的设置
GVIM [III] [u vimrc configuration]
2022PAGC 金帆奖 | 融云荣膺「年度杰出产品技术服务商」
LeetCode 648. Word replacement
UML sequence diagram (sequence diagram)
小程序目录结构
最长上升子序列模型 AcWing 482. 合唱队形
随机推荐
Cesium knows the longitude and latitude of one point and the distance to find the longitude and latitude of another point
NLLB-200:Meta开源新模型,可互译200种语言
[AI practice] Application xgboost Xgbregressor builds air quality prediction model (II)
libSGM的horizontal_path_aggregation程序解读
Selenium库
Million data document access of course design
Excellent open source system recommendation of ThinkPHP framework
Use day JS let time (displayed as minutes, hours, days, months, and so on)
Search engine interface
Oracle non automatic submission solution
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
请问,PTS对数据库压测有好方案么?
Parsing of XML files
Take you to master the three-tier architecture (recommended Collection)
Regular expression integer positive integer some basic expressions
请问,在使用flink sql sink数据到kafka的时候出现执行成功,但是kafka里面没有数
交换机和路由器的异同
一文读懂数仓中的pg_stat
call undefined function openssl_ cipher_ iv_ length
Hangdian oj2054 a = = B? ???