当前位置:网站首页>Getting started with cookies and sessions
Getting started with cookies and sessions
2022-06-23 09:28:00 【Java backend development】
HTTP It is a stateless protocol based on request and response .
Stateless means :
- Protocol has no memory for things to process , The server cannot automatically maintain user context information , Unable to save user state ;
- Each request is independent , Will not be affected by the previous request , It will not affect the subsequent requests .
Usually , Users access... Through a browser Web When applied , All servers need to save and track the status of users . Stateless protocol HTTP There is no way to meet this demand .
** Conversational Technology (Cookie and Session)** To solve this problem .
1、 Introduction to conversation Technology
Access a website from an open browser , To close the browser , It's called a conversation . Conversational technology refers to... In a conversation , Technology that helps the server record user status and data .
Common conversational techniques are Cookie and Session, among Cookie It's client session Technology ,Session Server session technology .
2、Cookie
Cookie, The original intention is “ cookies “, It is actually a short text message sent by the server to the browser , Stored in the memory of the client browser or on the hard disk . When the browser saves Cookie after , Every time you access the server , Will be in HTTP This is in the request header Cookie Send back to the server .
Cookie The creation of
javax.servlet.http The package defines a Cookie class , Using its construction method with parameters , You can create Cookie object .
Cookie c = new Cookie("url","www.baidu.com");
“url” yes Cookie The name of , Parameters name;“www.baidu.com” yes Cookie Value parameter of value.
Cookie The classification of :
- Session level Cookie( Default ):Cookie Save in browser memory , When the browser closes Cookie invalid .
- lasting Cookie:Cookie It is saved on the hard disk as a text file .
because Cookie By default, once the browser is closed ,Cookie Is the failure . But as we close the browser and then open the browser again to enter b standing , We are still logged in , There are many places where you need to use persistent Cookie. Set persistence Cookie Approach is to : call setMaxAge(int maxAge) Method to set the maximum effective time , In seconds .
Cookie workflow :
- The client browser accesses the server , The server passes through the HTTP Added in response Set-Cookie Field , Send data information to the browser ;
- The browser will Cookie Save in memory or hard disk ;
- When the browser accesses the server again , Browser through HTTP Add in request message Cookie Request header field , take Cookie Send it back to Web The server . Server according to Cookie Information tracks the status of the client .
Cookie Introductory example
The expected effect of the example is , When the user first accesses , Output : This is your first visit to this website ; When the user does not access for the first time , Output : Your last visit was :( The specific time of the last visit ).
package com.chen.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
// Save the last time the user visited
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// The server , Tell you , When you came , Take this time , Encapsulate into a letter , You bring it next time , I knew you were here
// Solve the Chinese garbled code
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
//Cookie The server gets it from the client
Cookie[] cookies = req.getCookies();// Here we return the array , explain Cookie There could be multiple
// Judge Cookie Whether there is
if (cookies != null){
// What if it exists
out.write(" The time of your last visit was :");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
// obtain cookie Name
if (cookie.getName().equals("lastLoginTime")){
// obtain cookie Value
long l = Long.parseLong(cookie.getValue());
Date date = new Date(l);
out.write(date.toString());
}
if (cookie.getName().equals("name")){
out.write(cookie.getValue());
}
}
}else{
out.write(" This is your first visit to this website ");
}
// The server gives the client a cookie
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
//cookie Valid for 1 God
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3、Session
When a browser accesses Web When the server's resources , The server can create one for each user browser Session object , Each browser has its own Session object . The exclusive method is that the server gives each browser a unique SessionID, It's like the student ID given to every student by a university .
Because each browser has one Session, So when users access the resources of the server , You can save the data in their own Session in , When the user accesses other resources in the server again , Other resources can be obtained from Session Retrieve data from , Serving users .
Session How it works :
Session The implementation of is inseparable from the client browser and Cookie Support for . We already know Cookie The technology is that the server sends data in name-value To the browser , Let the browser save , and Session It uses Cookie technology , Just leave the browser to save only SessionID, Other data is saved by the server .
Session and Cookie The difference between technologies , You can also see the difference in security between the two :Cookie It's clear text , Easy to disclose user information , Low security ; and Session The security is high . For all that ,Cookie Still widely used , because Cookie More efficient , For some information data that is not very important , use Cookie Also just as well .
Session It works as follows :
- When the client first requests a session , The server will create one Session object , And for this Session Object to assign a unique SessionID;
- Server will SessionID With Cookie(name=“JSESSONID”,value by SessionID Value ) Technology to the client browser ;
- When the client browser sends again HTTP When asked , Will carry SessionID Of Cookie Send it to the server ;
- The server reads from the request SessionID, And then according to SessionID Find the corresponding Session object .
Session The creation of
Session Objects are created by the server , adopt HttpServletRequest.getSession() Methods to get HttpSession object , for example :
HttpSession session = req.getSession();
Session Introductory example
package com.chen.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionDemo01 extends HttpServlet {
@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");
// obtain Session
HttpSession session = req.getSession();
// to Session There's something in it
session.setAttribute("name"," Qinjiang ");
// obtain Session Of ID
String id = session.getId();
// Judge Session Whether it is newly created
if(session.isNew()){
resp.getWriter().write("session Create success ,ID:"+id);
}else{
resp.getWriter().write("session It already exists in the server ,ID:"+id);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Session When objects are created ?
Session Object is called for the first time in the container req.getSession() Method . It is worth noting that , When the client accesses static resources , The server will not be created Session object .
Session Objects are destroyed 3 In this case :
- Session Out of date ;
- call session.invalidate() Method , Destroy by hand Session;
- The server is down or the application is uninstalled .
Session The default expiration time for is 30 minute , refer to Session From the time it is not used . We can set the expiration time in the following two ways .
The first method : stay web.xml Use... In the document < session-config > Elements :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- Set up session The expiration time of , The unit is minutes -->
<session-config>
<session-timeout>10</session-timeout>
</session-config>
</web-app>
If the set value is zero or negative , It means it will never expire
The second method : call setMaxInactiveInterval() Method
By calling session.setMaxInactiveInterval(int interval) Set expiration time , In seconds , Zero and negative numbers mean that the session will never expire , The code is as follows .
req.getSession().setMaxInactiveInterval(100);
4、Cookie vs Session
Cookie and Session It's all conversation technology , Can help the server save and track user status , But there are also differences :
- Different storage locations .Cookie Store the data in the memory of the client browser or on the hard disk ;Session Store data on the server side .
- Size and quantity limits differ .Cookie There are limits to the size and number of .
- Different types of data are stored .Cookie A string is saved in ;Session Objects are saved .
- Different security .Session More secure .
- The pressure on the server is different .Session It will consume a lot of server resources
边栏推荐
- Correspondence between three-tier architecture and SSM
- 也无风雨也无晴
- [nanopi2 trial experience] the first step of bare metal
- 微信小程序:点击按钮频繁切换,重叠自定义markers,但是值不改变
- [wangdingbei 2020 Qinglong formation]areuserialz
- Redis learning notes - AOF of persistence mechanism
- 什么是闭包函数
- 16. system startup process
- [geek Challenge 2019] hardsql
- Chain implementation of stack -- linear structure
猜你喜欢

Servlet-02 生命周期

Thin film interference data processing
![[geek challenge 2019] hardsql](/img/73/ebfb410296b8e950c9ac0cf00adc17.png)
[geek challenge 2019] hardsql

UEFI source code learning 3.7 - norflashdxe

UEFI source code learning 4.1 - pcihostbridgedxe

What is a closure function
Redis learning notes - single key management

16. system startup process

Simple student management
Redis learning notes - data type: hash
随机推荐
线性表(SequenceList)的顺序表示与实现----线性结构
扫码登录基本流程
Redis learning notes - Database Management
嵌入式系统概述(学习笔记)
Cookie和Session入门
[网鼎杯 2020 青龙组]AreUSerialz
Redis learning notes - slow query analysis
UEFI source code learning 4.1 - pcihostbridgedxe
Playing with nanopi 2 bare metal tutorial programming-01 lighting user led difficulty analysis
Servlet-02 生命周期
Redis learning notes - client communication protocol resp
基于mediapipe的手势数字识别
16. system startup process
线性表(LinkList)的链式表示和实现----线性结构
AI: the Elephant in Room
Learn SCI thesis drawing skills (f)
[SUCTF 2019]CheckIn
GPIO novice
Redis学习笔记—Pipeline
Redis learning notes - detailed explanation of redis benchmark