当前位置:网站首页>Detailed explanation of cookies and sessions
Detailed explanation of cookies and sessions
2022-06-26 16:07:00 【Hua Weiyun】
Conversational Technology
conversation : A session contains multiple requests and responses .
- One session : The first time a browser sends a request to a server resource , Session creation , Until one side is disconnected
function : Between multiple requests within the scope of a session , Shared data
The way : - Client session technology :Cookie
- Server side session technology :Session
Cookie
Concept
Client session technology , Save data to client
Quick start
Use steps :
- establish Cookie object , Data binding
new Cookie(String name, String value) - send out Cookie object
response.addCookie(Cookie cookie) - obtain Cookie, Get the data
Cookie[] request.getCookies()
Realization principle
Based on the response header set-cookie And the request header cookie Realization
cookie The details of the
- Can I send more than one at a time cookie?
You can create multiple Cookie object , Use response Call several times addCookie Method to send cookie that will do . - cookie How long to save in the browser ?
- By default , When the browser is closed ,Cookie The data is destroyed
- Persistent storage :
setMaxAge(int seconds) - Positive numbers : take Cookie The data is written to a file on the hard disk . Persistent storage . And designate cookie Survival time , After the time ,cookie The file is automatically invalidated
- negative : The default value is
- zero : Delete cookie Information
- cookie Can you save Chinese ?
stay tomcat 8 Before cookie Can't store Chinese data directly in .
- Need to transcode Chinese data — It is generally used URL code (%E3)
stay tomcat 8 after ,cookie Support Chinese data . Special characters are still not supported , It is recommended to use URL Encoding storage ,URL Decoding and parsing
- cookie Sharing issues ?
- Suppose it's in a tomcat Server , Deployed multiple web project , So in these web In the project cookie Can we share ?
- By default cookie Cannot share
- setPath(String path): Set up cookie The scope of acquisition . By default , Set the current virtual directory
- If you want to share , Then you can put path Set to "/"
- Different tomcat Server room cookie Sharing issues ?
setDomain(String path): If the primary domain name is the same , So many servers cookie Can be SharedsetDomain(".baidu.com"), that tieba.baidu.com and news.baidu.com in cookie Can be Shared
Cookie The characteristics and functions of
- cookie Store data in the client browser
- Browser for single cookie There is a limit to the size of (4kb) as well as For the total under the same domain name cookie There is also a limit to the number (20 individual )
effect :
- cookie Generally used to store a small amount of less sensitive data
- Without logging in , Complete the identification of the client by the server
Case study : Remember the last time you visited
demand
- Visit one Servlet, If it's a first visit , Prompt : Hello! , Welcome to .
- If it's not my first visit , Prompt : welcome back , Your last visit was : Display time string
analysis
- May adopt Cookie To complete
- On the server Servlet Determine if there is a name lastTime Of cookie
- Yes : Not for the first time
- The response data : welcome back , Your last visit was :2022 year 5 month 1 Japan 08:08:08
- Write back to Cookie:lastTime=2022 year 5 month 1 Japan 08:08:08
- No, : It's my first visit to
- The response data : Hello! , Welcome to
- Write back to Cookie:lastTime=2022 year 5 month 1 Japan 08:08:08
Code implementation
package cn.zjq.cookie;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.net.URLDecoder;import java.net.URLEncoder;import java.text.SimpleDateFormat;import java.util.Date;@WebServlet("/cookieTest")public class CookieTest extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the data format and encoding of the message body of the response response.setContentType("text/html;charset=utf-8"); //1. Get all Cookie Cookie[] cookies = request.getCookies(); boolean flag = false;// No, cookie by lastTime //2. Traverse cookie Array if(cookies != null && cookies.length > 0){ for (Cookie cookie : cookies) { //3. obtain cookie The name of String name = cookie.getName(); //4. Determine if the name is :lastTime if("lastTime".equals(name)){ // There is a reason Cookie, Not for the first time flag = true;// Yes lastTime Of cookie // Set up Cookie Of value // Get the string of the current time , To reset Cookie Value , To resend cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd Japan HH:mm:ss"); String str_date = sdf.format(date); System.out.println(" Before coding :"+str_date); //URL code str_date = URLEncoder.encode(str_date,"utf-8"); System.out.println(" After the coding :"+str_date); cookie.setValue(str_date); // Set up cookie Life time of cookie.setMaxAge(60 * 60 * 24 * 30);// A month response.addCookie(cookie); // The response data // obtain Cookie Of value, Time String value = cookie.getValue(); System.out.println(" Before decoding :"+value); //URL decode : value = URLDecoder.decode(value,"utf-8"); System.out.println(" After decoding :"+value); response.getWriter().write("<h1> welcome back , Your last visit was :"+value+"</h1>"); break; } } } if(cookies == null || cookies.length == 0 || flag == false){ // No, , First visit // Set up Cookie Of value // Get the string of the current time , To reset Cookie Value , To resend cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd Japan HH:mm:ss"); String str_date = sdf.format(date); System.out.println(" Before coding :"+str_date); //URL code str_date = URLEncoder.encode(str_date,"utf-8"); System.out.println(" After the coding :"+str_date); Cookie cookie = new Cookie("lastTime",str_date); // Set up cookie Life time of cookie.setMaxAge(60 * 60 * 24 * 30);// A month response.addCookie(cookie); response.getWriter().write("<h1> Hello! , Welcome to </h1>"); }} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); }}Session
Concept
Server side session technology , Sharing data among multiple requests in a session , Save the data in the object on the server side .HttpSession
Quick start
- obtain HttpSession object :
HttpSession session = request.getSession(); - Use HttpSession object :
Object getAttribute(String name)
void setAttribute(String name, Object value)
void removeAttribute(String name)
principle
Session The realization of depends on Cookie Of .
details
- When the client is shut down , The server does not shut down , Get twice session Is it the same ?
By default . No .
If you need the same , You can create Cookie, The key is JSESSIONID, Set the maximum lifetime , Give Way cookie Persistent save .
Cookie c = new Cookie("JSESSIONID",session.getId());c.setMaxAge(60*60);response.addCookie(c);- The client does not shut down , After the server is shut down , Acquired twice session Is it the same ?
Not the same , But make sure the data is not lost .tomcat Automatically complete the following work
- session Passivation of :
- Before the server is shut down properly , take session Serialize objects to hard disk
- session Activation of :
- After the server starts , take session The file is converted to... In memory session Object can .
- session When it was destroyed ?
- Server down
- session Object call invalidate() .
- session Default expiration time 30 minute
Optional configuration modification
<session-config> <session-timeout>30</session-timeout></session-config>Session Characteristics
- Session Data used to store multiple requests for a session , There is a server side .
- Session Can store any type , Data of any size .
Session And Cookie The difference between
- Session Store data on the server side ,Cookie On the client side
- Session There is no data size limit ,Cookie Yes
- Session Data security ,Cookie Relative to insecurity
边栏推荐
- 9 Tensorboard的使用
- Development, deployment and online process of NFT project (1)
- 【力扣刷题】二分查找:4. 寻找两个正序数组的中位数
- Stepn novice introduction and advanced
- redis的二进制数组命令
- stm32h7b0替代h750程序导致单片机挂掉无法烧录程序问题
- R language plotly visualization: Violin graph, multi category variable violin graph, grouped violin graph, split grouped violin graph, two groups of data in each violin graph, each group accounts for
- NFT合约基础知识讲解
- Application of ansible automation
- The details of the first pig heart transplantation were fully disclosed: human herpes virus was found in the patient, the weight of the heart doubled after death, and myocardial cell fibrosis
猜你喜欢

【力扣刷题】二分查找:4. 寻找两个正序数组的中位数

JS creative icon navigation menu switch background color

NFT合约基础知识讲解

振动式液量检测装置

Canvas three dot flashing animation

长安链交易防重之布谷鸟过滤器

Stepn débutant et avancé
Practice of federal learning in Tencent micro vision advertising

Big talk Domain Driven Design -- presentation layer and others

NFT Platform Security Guide (2)
随机推荐
Development, deployment and online process of NFT project (1)
11 introduction to CNN
Simple use of tensor
Redis顺序排序命令
C. Inversion Graph
Solidus Labs欢迎香港前金融创新主管赵嘉丽担任战略顾问
NFT transaction principle analysis (1)
Anaconda3安装tensorflow 2.0版本cpu和gpu安装,Win10系统
6 自定义层
SVG大写字母A动画js特效
请指教同花顺软件究竟是什么?网上开户是否安全么?
Cookie和Session详解
全面解析Discord安全问题
NFT contract basic knowledge explanation
Nanopi duo2 connection WiFi
2 three modeling methods
Stepn débutant et avancé
今年高考英语AI得分134,复旦武大校友这项研究有点意思
牛客小白月赛50
基于 MATLAB的自然过渡配音处理方案探究