当前位置:网站首页>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>
边栏推荐
- [untitled]
- Class loading mechanism
- HLS4ML/vivado HLS 报错解决方案
- 解决VSCode下载慢或下载失败的问题
- GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速
- Bao, what if the O & M 100+ server is a headache? Use Xingyun housekeeper!
- Oracle物理体系结构
- Uni app wechat applet one click login to obtain permission function
- Bind this of the current scope for callback functions in other cases such as timers and delayers
- 毕业季 | 华为专家亲授面试秘诀:如何拿到大厂高薪offer?
猜你喜欢
随机推荐
Cookie和Session的相关概念
大厂音视频职位面试题目--今日头条
JS 之 常用内置类的使用
Technology T3 domestic platform! Successfully equipped with "Yihui domestic real-time system sylixos"
How to configure webrtc video streaming format for easygbs, a new version of national standard gb28181 video platform?
集合对象值改变NULL值对象
[SQL optimization] the difference between with as and temporary tables
Ffmpeg audio related commands
MySQL signale une erreur can 't create table' demo01. TB Étudiant '(errno: 150)
Modsim basic use (Modbus simulator)
How to add transactions in JDBC
Anaconda安装虚拟环境到指定路径
[AI server setup] CUDA environment
Remove line breaks from MySQL query results
[exercise] HashSet
AAAI2020: Real-time Scene Text Detection with Differentiable Binarization
Bind this of the current scope for callback functions in other cases such as timers and delayers
Opencv video quality detection -- sharpness detection
Use the uni app demo provided by Huanxin to quickly realize one-on-one chat
墨天轮沙龙 | 清华乔嘉林:Apache IoTDB,源于清华,建设开源生态之路








