当前位置:网站首页>Related concepts of cookies and sessions
Related concepts of cookies and sessions
2022-07-01 19:48:00 【Dragon_ qing】
Cookie and Session Related concepts of
Cookie、Session
1. conversation
conversation : The user opens a browser , Click a lot of hyperlinks , Visit multiple web Dimension , Close the browser , This process can be called conversation
Stateful conversation : Sessions with access records
1. The server will give the client a cookie, When the client accesses next time, it will carry cookie Just visit cookie
2. The server registers that the client has accessed , Match to the client on the next access ; session
2. Two techniques for saving a session
cookie
- Client technology ( Respond to , request )
session
- Server technology , Using this technology , Can save user session information , Information or data can be stored in Session in .
Common scenes : After the website logs in , Don't log in again , The second visit went straight up !
3.Cookie
1. Get... From the request cookie Information
2. The server responds to the client cookie

cookie Related methods :
Cookie[] cookies = req.getCookies(); // get cookie
cookie.getName() // get cookie The key
cookie.getValue() // get cookie The value in
new Cookie("LastLoginTime",System.currentTimeMillis()+"") // Create a new one cookie
cookie.setMaxAge(24*60*60); // Set up cookie The period of validity
resp.addCookie(cookie); // The response gives the client a cookie
Case study :
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Solve the Chinese garbled code
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html; charset=utf-8");
PrintWriter out = resp.getWriter();
Cookie[] cookies = req.getCookies();
// Judge cookie Whether there is
if(cookies == null){
out.println(" First visit to the website ");
}else{
out.write(" Your last visit was :");
for (Cookie cookie : cookies) {
if("LastLoginTime".equals(cookie.getName())){
// obtain cookie The value in
long time = Long.parseLong(cookie.getValue());
Date date = new Date(time);
DateFormat dfd = DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.CHINA);
DateFormat dft = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CHINA);
out.write(dfd.format(date)+dft.format(date));
}
}
}
Cookie cookie = new Cookie("LastLoginTime",System.currentTimeMillis()+"");
// Set up cookie Valid for one day
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
cookie: It is usually saved in the local user directory appdate;
A website cookie Whether there is an upper limit ?
- One cookie Only one message can be saved ;
- One web Websites can send multiple messages to browsers cookie, At most 20 individual cookie;
- cookie There's a limit to the size 4kb
- 300 individual cookie Browser limit
Delete cookie:
- Do not set the validity period , Close the browser , Automatic failure ;
- Set the validity period to 0;
Be careful : stay cookie Is best used when the value of is in Chinese URLEncoder.encode() To code , Prevent Chinese miscoding . When taking value URLDecoder.decode() To decode .
4.Session( a key )
What's up? session:
- The server will create one for each user session object
- One session Monopolize a browser , As long as the browser is not closed , This Session There is a ;
- After the user logs in , The entire website is accessible --> Save user information ;

Session Common methods
Session and cookie The difference between :
- Cookie It is to write the user's data to the user's browser , Browser save ( You can save multiple )
- session Write the user's data to the user's exclusive Session in , Server side save ( Keep important information , Reduce the waste of server resources )
- session Objects are created by the server ;
Use scenarios :
- Save the information of a login user ;
- Shopping cart information ;
- Data often used throughout the website , We save it to Session in ;
Use session:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Solve the mess
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html; charset=utf-8");
PrintWriter out = resp.getWriter();
// obtain Session
HttpSession session = req.getSession();
// to session There's something in it
session.setAttribute("name",new Person(" Zhang San ",18));
// obtain session Of id
String id = session.getId();
// Judge session Is it newly created
if(session.isNew()){
out.write("session Create success ,ID:"+id);
}else{
out.write("session Already exist ,id:"+id);
}
//Session What did you do when you created it
// Cookie jsessionid = new Cookie("JSESSIONID", id);
// resp.addCookie(jsessionid);
}
//Person class
public class Person {
private String name;
private int age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
obtain session Information in
// obtain Session
HttpSession session = req.getSession();
Person name = (Person) session.getAttribute("name");
System.out.println(name);
Cancellation session
// obtain Session
HttpSession session = req.getSession();
session.removeAttribute("name");
// Cancellation session
session.invalidate();
Session expires automatically :web.xml To configure
<!-- Set up Session Default expiration time for -->
<session-config>
<!-- 15 Minutes later session Automatic failure , In minutes -->
<session-timeout>15</session-timeout>
</session-config>
边栏推荐
- Wechat applet navigator has a shadow after clicking. Remove the shadow effect of navigator
- Proxy in ES6
- 一文读懂C语言中的结构体
- Servlet knowledge points
- 【sql优化】with as 和 临时表的区别
- 【AI服务器搭建】CUDA环境
- 【无标题】
- Opencv video quality diagnosis - VIDEO occlusion diagnosis
- Technology T3 domestic platform! Successfully equipped with "Yihui domestic real-time system sylixos"
- servlet知识点
猜你喜欢

为定时器和延时器等其它情况的回调函数绑定当前作用域的this

通过js实现金字塔(星号金字塔,回文对称数字金字塔)

Mo Tianlun salon | Tsinghua qiaojialin: Apache iotdb, originated from Tsinghua, builds an open source ecological road

DTD modeling

大厂音视频职位面试题目--今日头条

Process steps of vibrating wire acquisition module for measuring vibrating wire sensor

Cookie和Session的相关概念

The key to the success of digital transformation enterprises is to create value with data
![[AI server setup] CUDA environment](/img/ca/2acfc42ea3ba24934a89472a8632f6.png)
[AI server setup] CUDA environment

wireshark报文分析tcp,ftp
随机推荐
Analysis of GetMessage underlying mechanism
Example explanation: move graph explorer to jupyterlab
Bind this of the current scope for callback functions in other cases such as timers and delayers
新窗口打开页面-window.open
Linux下安装Redis,并配置环境
Anaconda安装虚拟环境到指定路径
Interview questions for audio and video positions in Dachang -- today's headline
118. Yanghui triangle
Uni app product classification
Oracle物理体系结构
P2433 【深基1-2】小学数学 N 合一
[SQL optimization] the difference between with as and temporary tables
Ffmpeg avframe to cv:: mat
wireshark报文分析tcp,ftp
MySQl的基本使用
servlet知识点
list分割成满足和不满足条件的集合(partitioningBy)
Wechat applet realizes keyword highlighting
qobject_ Cast usage
振弦采集模塊測量振弦傳感器的流程步驟