当前位置:网站首页>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>
边栏推荐
- 今日群里分享的面试题
- optaplanner学习笔记(一)案例Cloud balance
- Shell advanced
- GC垃圾回收
- Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
- Oracle physical architecture
- Simplified pinduoduo product data
- Compile ffmpeg source code with msys+vs2019 under win10
- 大厂音视频职位面试题目--今日头条
- Test self-study people must see: how to find test items in software testing?
猜你喜欢

Why has instagram changed from a content sharing platform to a marketing tool? How do independent sellers use this tool?

Why must we move from Devops to bizdevops?

JS的Proxy

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

Audio and video, encoding and decoding related e-books, gadgets, packaged for free!

MySQl的基本使用

GB28181之SIP协议

What is the essential difference between Bi development and report development?

科技T3国产平台!成功搭载“翼辉国产实时系统SylixOS”

一个悄然崛起的国产软件,低调又强大!
随机推荐
Using win7 vulnerability to crack the system login password
Simplified pinduoduo product data
Wechat applet realizes keyword highlighting
tensorflow报错Could not load dynamic library ‘libcudnn.so.8
音视频、编解码相关电子书、小工具,打包奉送!
有意思了!数据库也搞Serverless!
JVM内存模型
通过js实现金字塔(星号金字塔,回文对称数字金字塔)
list分割成满足和不满足条件的集合(partitioningBy)
Bao, what if the O & M 100+ server is a headache? Use Xingyun housekeeper!
Object creation
1592 例题1 国王(Sgu223 LOJ10170 LUOGU1896 提高+/省选-) 暴力思考 状压DP 01背包
How to correctly use vertx to operate redis (3.9.4 with source code analysis)
optaplanner学习笔记(一)案例Cloud balance
Collect Tiktok video
A brief understanding of white box encryption technology
【sql优化】with as 和 临时表的区别
wireshark报文分析tcp,ftp
JDBC中如何添加事务
博途V16 获取系统时间转换成字符串