当前位置:网站首页>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 );
}
}
边栏推荐
- 6000多万铲屎官,捧得出一个国产主粮的春天吗?
- What is automated testing? What software projects are suitable for automated testing?
- Analog display of the module taking software verifies the correctness of the module taking data, and reversely converts the bin file of the lattice array to display
- In the era of industrial Internet, there are no more centers in the real sense, and these centers just turn tangible into intangible
- 利用微搭低代码实现级联选择
- Face pincher: a hot meta universe stylist
- How to distinguish PAAS, IAAs and SaaS?
- Huawei experimental topology set, learning methods are attached at the end of the article!
- [wustctf2020] climb
- Actual target shooting - skillfully use SMB to take down the off-line host
猜你喜欢

How to turn on win11 notebook power saving mode? How to open win11 computer power saving mode

只显示两行,超出部分省略号显示
![[image fusion] multi focus and multi spectral image fusion based on pixel saliency and wavelet transform with matlab code](/img/78/5d8ad56d4ff1451590cc8676893f05.png)
[image fusion] multi focus and multi spectral image fusion based on pixel saliency and wavelet transform with matlab code
![选择器(>,~,+,[])](/img/7e/2becfcf7a7b2e743772deee5916caf.png)
选择器(>,~,+,[])

两个链表的第一个公共节点_链表中环的入口(剑指offer)

Face pincher: a hot meta universe stylist
![[pointnet] matlab simulation of 3D point cloud target classification and recognition based on pointnet](/img/86/5db689cdac2a927a23dff3fb9594b0.png)
[pointnet] matlab simulation of 3D point cloud target classification and recognition based on pointnet
![[equalizer] bit error rate performance comparison simulation of LS equalizer, def equalizer and LMMSE equalizer](/img/45/61258aa20cd287047c028f220b7f7a.png)
[equalizer] bit error rate performance comparison simulation of LS equalizer, def equalizer and LMMSE equalizer

捏脸师: 炙手可热的元宇宙造型师

bjdctf_ 2020_ babystack
随机推荐
[learn FPGA programming from scratch -41]: vision chapter - Moore's era and Moore's law and the arrival of the post Moore Era
Huawei cloud image engine service
游戏思考14:对cache_server缓冲服务器的问题思考(读云峰博客有感)
Combine with (& &) logic or (||), dynamic binding and ternary operation
Learning to use BACnet gateway of building control system is not so difficult
[从零开始学习FPGA编程-42]:视野篇 - 后摩尔时代”芯片设计的技术演进-1-现状
只显示两行,超出部分省略号显示
[WUSTCTF2020]alison_likes_jojo
Summary of 2022 blue team HW elementary interview questions
与(&&)逻辑或(||),动态绑定结合三目运算
Analog display of the module taking software verifies the correctness of the module taking data, and reversely converts the bin file of the lattice array to display
What is an intrusion detection system?
華為雲數據庫進階學習
[机缘参悟-29]:鬼谷子-内揵篇-与上司交往的五种层次
MaxCompute远程连接,上传、下载数据文件操作
What are the dazzling skills of spot gold?
bjdctf_2020_babystack
Virtual machine security disaster recovery construction
What is a CC attack? How to judge whether a website is attacked by CC? How to defend against CC attacks?
第三方软件测试公司如何选择?2022国内软件测试机构排名