当前位置:网站首页>[web] cookies and sessions
[web] cookies and sessions
2022-06-13 03:49:00 【Bryant tapping the code】
Blog home page : Bryant typing the code
Welcome to thumb up Collection Leaving a message. Welcome to discuss !
This paper is written by 【 Bryant typing the code 】 original , First appeared in CSDN
Because the blogger is learning Xiaobai one , There are bound to be mistakes , If you have any questions, please leave a message in the comment area to point out , Be deeply grateful !
Boutique column ( Update from time to time )【JavaSE】 【Java data structure 】【LeetCode】
【Web】Cookie and Session
review Cookie
HTTP The agreement itself belongs to “ No state ” agreement .
“ No state ” Means :
By default HTTP This communication between the client and server of the protocol , There is no direct connection with the next communication .
But in actual development , We often need to know the relationship between requests .
For example, after successfully logging in to the website , During the second visit, the server can know whether the request has been logged in .

adopt set-cookie Return to the browser and store in Cookie Things in fields are like A token given by the server to the client Used for identification and identification
At this time in The server We need it here Record token information , And the user information corresponding to the token , This is Session The work done by the mechanism .
Understanding conversational mechanisms (Session)
The server receives many requests at the same time . The server needs to be cleared to distinguish which user each request belongs to , You need to record the corresponding relationship between each user token and user information on the server side .
It's like going to the hospital , A doctor's card is a card “ token ”. For this token to work , The hospital needs to record the relationship between each visit card and patient information through the system .
The essence of conversation is a “ Hashtable ”, Stored some key value pair structures . key Namely Token ID(token/sessionId), value Namely User information ( User information can be flexibly designed according to requirements ).
sessionIdIs a generated by the server “ Uniqueness string ”, from session From the perspective of mechanism , This unique string is called “sessionId”. But look at it in the whole login process , You can also call this unique string “token”. sessionId and token It can be understood as different names of the same thing ( Different perspectives )

Servlet Of Session The default is stored in memory .
If you restart the server Session The data is lost .
Cookie and Session The difference between
- Cookie yes
clientThe mechanism of . Session yesServer sideThe mechanism of . - Cookie and Session Often used together . But you don't have to cooperate .
- It can be used completely Cookie To save some data on the client . These data are not necessarily user identity information , It doesn't have to be
token / sessionId - Session Medium token / sessionId You don't have to pass Cookie / Set-Cookie Pass on .
The core approach
HttpServletRequest Related methods in class
| Method | describe |
|---|---|
| HttpSession getSession() | Get the session in the server . If the parameter is true, Create a new session when there is no session ; If the parameter is false, Returns... When there is no session null |
| Cookie[ ] getCookies() | Returns an array , Contains all of the Cookie object . Will automatically Cookie The format in is parsed into key value pairs . |
HttpServletResponse Related methods in class
| Method | describe |
|---|---|
| void addCookie(Cookie cookie) | The specified cookie Add to response . |
HttpSession Related methods in class
One HttpSession Inside the object
Contains multiple key value pairs. WeYou can go HttpSession Save any information we need.
| Method | describe |
|---|---|
| Object getAttribute(Stringname) | The method returns the value in the session The object with the specified name in the session , If there is no object with the specified name , Then return to null. |
| void setAttribute(Stringname, Object value) | This method binds an object to the object with the specified name session conversation boolean isNew() Determine whether the current session is a newly created session |
Cookie Related methods in class
Every Cookie An object is a key value pair .
| Method | describe |
|---|---|
| String getName() | This method returns cookie The name of . The name cannot be changed after creation .( This value is SetCooke Field set to the browser ) |
| String getValue() | This method obtains and cookie The value of the Association |
| void setValue(StringnewValue) | This method is set up with cookie The value of the Association . |
- HTTP Of Cooke What is stored in the field is actually multiple sets of key value pairs . Each key value pair is in Servlet All correspond to one Cookie object .
- adopt HttpServletRequest.getCookies() Get a series of... In the request Cookie Key value pair .
- adopt HttpServletResponse.addCookie() You can add a new... To the response Cookie Key value pair .
Code example : Realize user login
Implement simple user login logic
This code is mainly through HttpSession class complete . We don't need to operate it manually Cookie object .
1. Achieve a landing page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> land </title>
</head>
<body>
<form action="login" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value=" Submit ">
</form>
</body>
</html>
2. Achieve one Servlet Used to process login requests
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html; charset=utf-8");
// 1. Get the user name and password submitted by the user
String username = req.getParameter("username");
String password = req.getParameter("password");
// 2. Determine whether the user name and password are correct
if (!username.equals("kobe") || !password.equals("824")) {
// Login failed
resp.getWriter().write(" Login failed ");
return;
}
// Landing successful
System.out.println(" Landing successful ");
// Set up Session
HttpSession session = req.getSession(true);
session.setAttribute("username", "Kobe Bryant");
session.setAttribute("loginCount", "");
resp.sendRedirect("index");
}
}


3. One more IndexServlet To represent the home page after redirection
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/index")
public class IndexServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html; charset=utf-8");
// 1. Determine whether the current user has logged in
HttpSession session = req.getSession(false);
if (session == null) {
// The user didn't log in , Redirect to login.html
resp.sendRedirect("login.html");
return;
}
// 2. If you have logged in , From Session Fetch the number of accesses data from
String userName = (String)session.getAttribute("username");
String countString = (String)session.getAttribute("loginCount");
int loginCount = Integer.parseInt(countString);
loginCount += 1;
session.setAttribute("loginCount", loginCount + "");
// 3. Show on page .
StringBuilder html = new StringBuilder();
html.append(String.format("<div> user name : %s</div>", userName));
html.append(String.format("<div>loginCount: %d</div>", loginCount));
resp.getWriter().write(html.toString());
}
}

Realization effect


边栏推荐
- Binocular vision -- creating an "optimal solution" for outdoor obstacle avoidance
- Synching build your own synchronization cloud
- 机器人避障系统基础
- 【Web】Cookie 和 Session
- 【测试开发】博客系统——Loadrunner性能测试(发布博客功能 基准测试)
- Lambda终结操作collect
- 【面试复习】自用不定时更新
- 【测试开发】测试的相关基本概念
- LeetCode 178. Score ranking (MySQL)
- Spark Optimization -- differences and policy selection of RDD cache (cache, persist, checkpoint)
猜你喜欢

【youcans 的 OpenCV 例程200篇】201. 图像的颜色空间转换

SQL injection case demonstration and preventive measures

CDN domain name

Explain usage, field explanations, and optimization instances of MySQL
![[200 opencv routines by youcans] 201 Color space conversion of images](/img/99/36ba75cda08fd816dce83eaeea9e8d.png)
[200 opencv routines by youcans] 201 Color space conversion of images

USB-IF BC1.2充电协议解读

5G China unicom 直放站 网管协议 实时性要求

UDP connection map collection

Spark optimization - Performance (general performance, operator, shuffle, JVM) tuning
![[test development] automatic test selenium (I)](/img/cd/b6dc4ac53b4f30f745ec0590ac384b.png)
[test development] automatic test selenium (I)
随机推荐
Database object, sequence, view, index
【面试复习】自用不定时更新
How can a sweeping robot avoid obstacles without "mental retardation"? Analysis of five mainstream obstacle avoidance techniques
单片机:A/D 差分输入信号
Lambda end operation find and match findfirst
Use of Oracle PL-SQL
Serialization & deserialization
2022春学期总结
Talking about the wavelength of laser radar
Spark optimization - Performance (general performance, operator, shuffle, JVM) tuning
Lambda终结操作查找与匹配noneMatch
Precautions for stream flow
单片机:Modbus 通信协议介绍
【测试开发】用例篇
【愚公系列】2022年06月 .NET架构班 081-分布式中间件 ScheduleMaster的API自定义任务
5G China unicom AP:B SMS ASCII 转码要求
Workflow of driver of spark kernel (stage division, task division, task scheduling)
单片机外设介绍:温度传感器 DS18B20
Getting started with Oracle
单片机信号发生器程序
