当前位置:网站首页>Session & cookie details
Session & cookie details
2022-06-24 07:33:00 【Laziness 187】
conversation
conversation : When the browser opens , Access to the server Indicates the beginning of the session
Session in progress : Communication between browser and server ( One communication Multiple communications )
End of session : When the browser closes , End of session
Session problems : Data generated in the session Need to save
A session is a process of interaction between a browser and a server , Data must be generated in the session , Valid data and invalid data , Valid data may need to be saved , Memory of the saved location , Hard disk . We can exist on the browser side perhaps Server side
Conversational Technology
Conversational Technology :
effect : Save the data
Browser side technology : cookie
Server side technology : session
cookie
Session level cookie
OneServlet
public class OneServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("OneServlet");
//1. There is data to save establish cookie
Cookie cookie = new Cookie("ds" , "meimei");
//2. take cookie Respond to the browser
response.addCookie( cookie );
}
}
TwoServlet
public class TwoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("TwoServlet");
// Get the information delivered by the browser cookie
Cookie[] cookies = request.getCookies();
// Traversing an array
// All... Contained in this request Cookie Array of , If the request does not cookie, Then return to null
if(cookies != null ){
// Traverse cookie
//Idea-a04ab689 @@ b23c0a93-4c5e-4a7e-9125-9dbc273d9498
// This is idea Version problem Some versions produce a cookie
for (Cookie cookie : cookies) {
//name Express cookie The name of value Express cookie Value
System.out.println( cookie.getName() +" @@ "+cookie.getValue() );
}
}else{
System.out.println(" No, cookie data ");
}
}
}
Summary :
The default browser closes cookie disappear , Conversation level cookie , End of session cookie It doesn't work
Cookie cookie = new Cookie(name , value); establish cookie
response.addCookie( cookie ); Respond to cookie
Cookie[] cookies = request.getCookies(); get cookie
cookie Is saved in the browser , Different browsers Cannot share cookie
Persistence level cookie
cookie.setMaxAge( Time ); Set up cookie Maximum survival time Unit second
cookie.setPath( ) Set the path
cookie Details
/** * cookie Small details of : * 1.cookie No Chinese support , tomcat8 I've dealt with tomcat 7 Not dealt with ( No Chinese support ) * 2.cookie follow 423 The rules of ( The old saying goes ) * 4 Express 4kb: cookie The length of should not be too long Maximum 4kb( Precise ) * 2 Express 20 individual : A website supports the largest cookie Number 20 individual ( Imprecise ) * 3 Express 300 individual : The whole browser All the websites add up cookie 300 individual ( Imprecise ) * @param request * @param response * @throws ServletException * @throws IOException */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("OneAPIServlet");
//1. There is data to save establish cookie
Cookie cookie = new Cookie("ds" , " ha-ha ");
// Set up cookie Properties of
// Set up cookie Maximum effective lifetime Company : second
cookie.setMaxAge( 0 );
/** * Set up path route * path The meaning is : * 1. Indicates that the request is sent to the server again cookie Basis for automatic carrying Must satisfy path Or path All subdirectories are OK * path : localhost/day05 * localhost:8080/day05/a/b/c resources It'll carry it automatically cookie subdirectories * localhost:8080/day05/a resources It'll carry it automatically cookie Same path * localhost:8080/day05/a/a.html resources It'll carry it automatically cookie subdirectories * localhost:8080/day06/a resources Will not automatically carry cookie Does not conform to the path * www.baidu.com:8080/day06/a resources Will not automatically carry cookie Does not conform to the path * 2.path and name decision cookie Is it the only * cookie You can have the same name locally As long as it is placed path The path is different * Summary : Be careful , When setting the path later General advice cookie.setPath("/"); Try not to carry the project name * A company Ten projects Ten projects cookie Suggestions are shared * Set to localhost/ Subsequent projects localhost/day05 localhost/day06 You can visit this cookie * * problem 1: If it covers cookie? * name + path Must follow the previous cookie Corresponding * problem 2: How to delete cookie? * (name + path) Cover + Time ( Lapse immediately ) No direct deletion cookie Of api */
cookie.setPath("/");
//2. take cookie Respond to the browser
response.addCookie( cookie );
}
Record the last visit time

/** * Output the last access time of the user , Record the user's current login time * @param request * @param response * @throws ServletException * @throws IOException */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Prevent confusion code
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//1. Determine whether the user is visiting for the first time or for the second time N visit
// get cookie
Cookie[] cookies = request.getCookies();
boolean flag = false; // The default is false
String cookieValue = null;// Define a cookie Value
if(cookies != null ){
// The first visit or the N visit It doesn't mean the first time Nor does it mean that N Time Not sure
// There are other cookie for example ds But it's not lastTime
for (Cookie cookie : cookies) {
if( "lastTime".equals(cookie.getName()) ){
// If you can get into if It means There is last time It means the first one N visit
cookieValue = cookie.getValue();
flag=true;
}//else{// First visit ? hypothesis ds dzd username lastTime nickname
//}
}
}//else{// First visit No, cookie signify No, lastTime First visit
//}
if(flag == true ){
// The first N visit
//3. The first N visit Output your last access time as ....
// Get the last visit time
// The result is the result before coding Must also decode
String decode = URLDecoder.decode(cookieValue, "utf-8");
System.out.println(" Your last visit was :"+ decode +" @@" +cookieValue );
// Overwrite the local time again Cover cookie On the condition that : path + name As like as two peas
String date = new Date().toLocaleString();// Creation time
String encode = URLEncoder.encode(date, "utf-8");// code
Cookie cookie = new Cookie("lastTime" , encode);
cookie.setMaxAge(60*60); // Set the effective time
cookie.setPath("/");// Set the path
response.addCookie( cookie );
}else{
// First visit
//2. First visit Output is your first visit
// Report errors :java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value
//cookie Not all special symbols are supported code : Change the original characters into other symbols To restore symbols Decode it
String date = new Date().toLocaleString();
// code : use URL code (jdk Bring your own tools )
// Parameters 1: A string that needs to be encoded Parameters 2: Later decoded code table
String encode = URLEncoder.encode(date, "utf-8");
System.out.println(" This is the first time you access the time before compilation :" +date + " @@ Time after compilation :" +encode );
Cookie cookie = new Cookie("lastTime" , encode);
cookie.setMaxAge(60*60); // Set the effective time
cookie.setPath("/");// Set the path
response.addCookie( cookie );
}
}
边栏推荐
- [image fusion] image fusion based on NSST and PCNN with matlab code
- [TS] function type
- 10 common malware detection and analysis platforms
- MFC multithreaded semaphore csemaphore critical area and mutually exclusive events
- Huawei cloud image engine service
- Tutorial on simple use of Modbus to BACnet gateway
- Camera calibration (calibration purpose and principle)
- Win11怎么设置让CPU性能全开?Win11CPU怎么设置高性能模式?
- Prefix and topic training
- 现货黄金有哪些眩人的小技术?
猜你喜欢

Learning to use BACnet gateway of building control system is not so difficult

In JS, the regular expression verifies the hour and minute, and converts the input string to the corresponding hour and minute

电脑如何打开软键盘,教大家Win10如何打开软键盘的方法

20个不容错过的ES6技巧

【信号识别】基于深度学习CNN实现信号调制分类附matlab代码

Big factories are not the only way to measure ability. The three years' experience of Shangcai's graduation

How to delete / select an input method on your computer

现货黄金有哪些值得借鉴的心态

二分专题训练

Ultra wideband pulse positioning scheme, UWB precise positioning technology, wireless indoor positioning application
随机推荐
How to turn on win11 notebook power saving mode? How to open win11 computer power saving mode
What are the dazzling skills of spot gold?
【MySQL 使用秘籍】克隆数据表、保存查询数据至数据表以及创建临时表
bjdctf_2020_babystack
Face pincher: a hot meta universe stylist
捏脸师: 炙手可热的元宇宙造型师
[learn FPGA programming from scratch -41]: vision chapter - Moore's era and Moore's law and the arrival of the post Moore Era
How can win11 set the CPU performance to be fully turned on? How does win11cpu set high performance mode?
电脑如何打开软键盘,教大家Win10如何打开软键盘的方法
Fine! Storage knowledge is a must for network engineers!
[MySQL usage Script] clone data tables, save query data to data tables, and create temporary tables
Web messaging and woker classification: talking about the cross thread and cross page communication of PostMessage
Tencent cloud security and privacy computing has passed the evaluation of the ICT Institute and obtained national recognition
How to open the soft keyboard in the computer, and how to open the soft keyboard in win10
两个链表的第一个公共节点_链表中环的入口(剑指offer)
自动化测试是什么?什么软件项目适合自动化测试?
OMX initialization process
【图像融合】基于伪 Wigner 分布 (PWD) 实现图像融合附matlab代码
How can genetic testing help patients fight disease?
2、 What is the principle of layer 3 and 4 switching technology? Recommended collection!