当前位置:网站首页>Cookie Technology & session Technology & ServletContext object
Cookie Technology & session Technology & ServletContext object
2022-07-06 07:05:00 【aigo-2021】
One 、Cookie technology
Http The agreement has one feature , Namely No state , The data of each request response is not persisted . But I'm doing something Web When needed , It is necessary to record the user's status .
Cookie Technology can record some user information on the client . adopt ServletAPI Provided in Cookie class , Data can be stored in the client cookie In file , When sending a request ,cookie The contents of the file are contained in http In request .
Realize data passing Cookie Store on client , Create on the server side Cookie Class object , Encapsulate data into Cookie In the object , adopt response Object will Cookie Object responds back to the client , The client will automatically Cookie The data of is stored in the folder specified by the client Cookie In file .
for example : Visit one TestServlet1 Send a name Store to client :
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;
@WebServlet("/text1.do")
public class TestServlet1 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// take tom name Store to access this Servlet On the client side of
Cookie cookie = new Cookie("name1","tom");
cookie.setMaxAge(60*60*24);
resp.addCookie(cookie);
Cookie cookie1 = new Cookie("name2","jack");
cookie1.setMaxAge(60*60*24);
resp.addCookie(cookie1);
Cookie cookie2 = new Cookie("password","123");
cookie2.setMaxAge(60*60*24);
resp.addCookie(cookie2);
}
}
Access in browser http:localhost:8080/emp/text1.do View the stored Cookie data
You can visit a site , Get the... Of this site in the request Cookie data ( Client's )
@WebServlet("/text2.do")
public class TestServlet2 extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
// get Client stored Cookie
Cookie[] cookies = request.getCookies();
for(Cookie cookie:cookies){
System.out.println(cookie.getName()+","+cookie.getValue());
}
}
}
Two 、Session technology
Session Is the meaning of conversation , A session object representing the client and server , An object stored on the server .
When the client accesses the server , A session object will be created on the server , When the client accesses the server again , This session object is still used , No request response is generated within the validity of the session object , The session object will be destroyed ,tomcat Of session The default validity period of is 20 minute
There is a hash table storing session objects on the server ( Hashtable ), When the browser accesses the server , The server reads the browser Cookie Zhongcun Stored session id.
3、 ... and 、Session Object lifecycle
because Session It has a long life cycle , Can be directed to Session Store some data in , Then the life cycle of these data is equivalent to session Life week of period , For example, how long does the login status need to be saved ? As long as there is a request response operation , You need to save the login status .
How to talk to Session Medium storage data :
HttpSession The interface provides setAttribute Method , Can be directed to Session Object to store data .
Store the data
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/text1.do")
public class TestServlet1 extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
// towards Session Object full name tom
// First, get session object
HttpSession session = request.getSession();
//session Object encapsulates a Map object , Stored data in Map in , Generally speaking, it is stored in Session Properties of
session.setAttribute("name1","tom");//key,value Form storage of
}
}
get data
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/text2.do")
public class TestServlet2 extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
// obtain Session Data in
HttpSession session = request.getSession();
System.out.println(session.getAttribute("name1"));
}
}
get Session data , First visit text1.do, Revisit text2.do
Four 、 Set up Session The period of validity
stay web.xml in , Set up session The period of validity , The unit is minutes
<session-config>
<session-timeout>1</session-timeout><!-- Set to 1 minute -->
</session-config>
Is there any request response within the validity period ,Session Be destroyed
Of course , You can also call HttpSession Methods , Give Way Session Object invalidation
// Give Way session invalid
session.invalidate();
session Invalidation and destruction are different ,session The attribute value cannot be obtained after expiration , Nor can it fail again , Can't do these operations , but session Object still exists ;session The destruction of objects is Session The object doesn't exist , wipe out .
5、 ... and 、ServletContext object
ServletContext yes Servlet Context object , Also called application context object . stay Web The server (tomcat) Startup time ServletContext Object created ,Web When the server is destroyed ,ServletContext Object destroyed .
ServletContext Object lifecycle Longer than Session
Can be directed to ServletContext Object to store some data , The life cycle of data is related to ServletContext The life cycle is the same . through setAttribute and getAttribute Method to store and obtain
reflection :
What kind of data exists Session in ? What kind of data exists ServletContext in ?
The data shared by each page is stored in Session in ; Data shared by all users is stored in ServletContext in
边栏推荐
- Map of mL: Based on the adult census income two classification prediction data set (whether the predicted annual income exceeds 50K), use the map value to realize the interpretable case of xgboost mod
- 简单描述 MySQL 中,索引,主键,唯一索引,联合索引 的区别,对数据库的性能有什么影响(从读写两方面)
- Do you really know the use of idea?
- Chapter 7 - thread pool of shared model
- Briefly describe the differences between indexes, primary keys, unique indexes, and joint indexes in mysql, and how they affect the performance of the database (in terms of reading and writing)
- The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
- OpenGL ES 学习初识(1)
- Blue Bridge Cup zero Foundation National Championship - day 20
- Setting and using richview trvstyle template style
- leetcode841. Keys and rooms (medium)
猜你喜欢
LeetCode 78:子集
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
leetcode841. 钥匙和房间(中等)
idea控制台彩色日志
顶测分享:想转行,这些问题一定要考虑清楚!
【服务器数据恢复】IBM服务器raid5两块硬盘离线数据恢复案例
Babbitt | metauniverse daily must read: the group image of Chinese Internet enterprises pouring into metauniverse: "there are only various survival desires, and there is no ambition for forward-lookin
微信公众号无限回调授权系统源码 全网首发
18.多级页表与快表
AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models. common‘ from ‘/home/yolov5/models/comm
随机推荐
[brush questions] how can we correctly meet the interview?
UWA pipeline version 2.2.1 update instructions
Leetcode35. search the insertion position (simple, find the insertion position, different writing methods)
C语言_双创建、前插,尾插,遍历,删除
The psychological process from autojs to ice fox intelligent assistance
PCL实现选框裁剪点云
[advanced software testing step 1] basic knowledge of automated testing
The first Baidu push plug-in of dream weaving fully automatic collection Optimization SEO collection module
AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models.common‘ from ‘/home/yolov5/models/comm
漏了监控:Zabbix对Eureka instance状态监控
微信脑力比拼答题小程序_支持流量主带最新题库文件
Three methods of adding color to latex text
Librosa audio processing tutorial
Wechat brain competition answer applet_ Support the flow main belt with the latest question bank file
将ue4程序嵌入qt界面显示
Internal and external troubles of "boring ape" bayc
What does UDP attack mean? UDP attack prevention measures
Fedora/rehl installation semanage
Embed UE4 program into QT interface display
SSO process analysis