当前位置:网站首页>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>
边栏推荐
- Optimization of video streaming with repeated requests in the case of unstable easygbs network
- Technology T3 domestic platform! Successfully equipped with "Yihui domestic real-time system sylixos"
- ffmpeg 错误码
- windows环境 redis安装和启动(后台启动)
- 【无标题】
- JS 之 常用内置类的使用
- DTD modeling
- ModSim基本使用(Modbus模拟器)
- What is the essential difference between Bi development and report development?
- Wechat applet realizes keyword highlighting
猜你喜欢
How to correctly use vertx to operate redis (3.9.4 with source code analysis)
Object creation
Axure does not display catalogs
Introduction and installation of crunch, and making password dictionary with crunch
optaplanner学习笔记(一)案例Cloud balance
【AI服务器搭建】CUDA环境
HLS4ML报错The board_part definition was not found for tul.com.tw:pynq-z2:part0:1.0.
wireshark报文分析tcp,ftp
servlet知识点
Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
随机推荐
P2433 【深基1-2】小学数学 N 合一
mysql 报错 Can‘t create table ‘demo01.tb_Student‘ (errno: 150)*
DS Transunet:用于医学图像分割的双Swin-Transformer U-Net
Brpc understanding
【无标题】
[research materials] iResearch tide Watching: seven major trends in the clothing industry - Download attached
The key to the success of digital transformation enterprises is to create value with data
PowerDesigner设计Name和Comment 替换
实例讲解将Graph Explorer搬上JupyterLab
振弦采集模塊測量振弦傳感器的流程步驟
Opencv video quality diagnosis - VIDEO occlusion diagnosis
Class loading mechanism
Shell advanced
博途V16 获取系统时间转换成字符串
SIP protocol of gb28181
JS ternary expression complex condition judgment
Optimization of video streaming with repeated requests in the case of unstable easygbs network
What is the essential difference between Bi development and report development?
How to configure webrtc video streaming format for easygbs, a new version of national standard gb28181 video platform?
How to correctly use vertx to operate redis (3.9.4 with source code analysis)