当前位置:网站首页>Cookies and sessions
Cookies and sessions
2022-06-12 16:22:00 【A snail at the end of a pyramid】
Catalog
Cookie and Session
Go to the registration office of the hospital , You will get a doctor card , The card contains key information about the current patient ( amount to cookie).
You can swipe your doctor card in every department , When you swipe your doctor card , You can use the server of the hospital , To get a series of information about the current patient .( It's not just identity information , There are also previous cases )
Visit card is equivalent to Cookie
On the data server of the hospital , It saves the user's information , That is, through session The way to save .
HttpServletRequest Related methods in class
getSession
HttpServletRequest Related methods in class .
Calling getSession The specific things to do when
- Create a session
First, get the request cookie Inside sessionId Field ( It is equivalent to the identity of the session )
Judge this sessionId Whether there is..., on the current server
If it doesn't exist , Enter the create session logic .
Create a session : Will create a HttpSession object , And generate a sessionId, Then we'll put this sessionId As key, Put this HttpSession Object as value, Put this key value right , Give a to save to the server memory “ Hashtable ” In such a structure .
After that , The server will return a HTTP Respond to , hold sessionId adopt Set-Cookie Field is returned to the browser .
The browser can save this sessionId To Cookie It's in .
It doesn't have to be a hash table , But it must be a similar structure that can store key value pairs , And the data is in memory .
- Get session
Get the... In the request first cookie Inside sessionId Field ( It is also the identity of the session )
Judge this sessionId Whether there is..., on the current server ( That is, whether there is any in the hash table )
If there is , Just query this directly HttpSession object , And return by return value .
HttpSession
This object is also a “ Key value pair ” Structure .
HttpSession Each key value pair inside , be called “ attribute ”(Attribute).
HttpSession There are two ways
(1)getAttribute( Take key value pairs )
(2)setAttribute( Save key value pairs )
getCookies
Cookie[] getCookies(): Get... In the request Cookie data .
The return value is Cookie An array of types , Each element is a Cookie object , Every Cookie The object contains two more properties ,name and value( Or key value pairs )
HTTP In the request cookie Fields are organized in key value pairs , The key value pairs here , General format , Use ; To split multiple key value pairs , Use = To split keys and values , These key value pairs will pass in the request cookie Field is passed to the server . After the server receives the request , It will be parsed , It can be interpreted as Cookie[] Form like this .

Cookie Here you can save any customized key value pairs
If it is a general key value pair , Use it directly getCookies To get
If it is a special key value pair ( Express sessionId The key/value pair ), No need to use getCookies, Use it directly getSession, Just help us automatically from Cookie To take sessionId 了 .
HttpServletResponse Related methods in class

The response can be based on addCookie This method , To add a Cookie Information into the response message .
The key value pairs added here , Will act as HTTP In response set-Cookie Fields to represent .
Website login
Click the login button , Will send a login request to the server .

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Handling user requests
String username=req.getParameter("username");
String password=req.getParameter("password");
// Determine whether the user name and password are correct
// Normally , This decision operation should be placed in the database for access
// Here for simplicity , Just write it in the code , Suppose the user name is "zhangsan", The password is "123"
if("zhangsan".equals(username) && "123".equals(password)) {
// Login successful
resp.sendRedirect("index");
}else {
// Login failed
resp.getWriter().write("login failed");
}
}
}
In the following jump to index When , The server should be able to obtain the identity information of the current user , So you need to create a session For later use . And in session Fill in some necessary identity information in the , For later use .
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Handling user requests
String username=req.getParameter("username");
String password=req.getParameter("password");
// Determine whether the user name and password are correct
// Normally , This decision operation should be placed in the database for access
// Here for simplicity , Just write it in the code , Suppose the user name is "zhangsan", The password is "123"
if("zhangsan".equals(username) && "123".equals(password)) {
// Login successful
// Create a session , Save the necessary identity information
HttpSession httpSession= req.getSession(true);
// Store key value pairs into the session , Necessary identification information
httpSession.setAttribute("username",username);
resp.sendRedirect("index");
}else {
// Login failed
resp.getWriter().write("login failed");
}
}
}
@WebServlet("/index")
public class IndexServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Return to a home page ( The home page is a simple html fragment )
// You need to get the user name , from httpsession You can get it in the middle
// here getSession The parameter of must be false, In the previous login process , The session has been created , Here is to get the previous session directly
HttpSession session=req.getSession(false);
String username=(String)session.getAttribute("username");
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("<h3> Welcome "+username+"</h3>");
}
}
<body>
<form action="login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value=" Sign in ">
</form>
</body>
In conversation , Can save any specified user information
Here, , You can realize a function , Record the number of times the current user has visited the home page .
After logging in , First visit home , On the home page , Currently accessed 1 Time , When you refresh the page , The times will add up .
Upload files
It is also a typical requirement in development 
When uploading files , At the front end, you need form Forms
form In the form , Need to use a special type form-data
This is the time to submit documents , The browser will put the contents of the file as form-data The format of is constructed to HTTP In request . The server can use getPart To get .
One HTTP request , You can submit multiple files at once
Each file is called a part, Every part There is one. name( Identification ), Server code can be based on name Find the corresponding part.
Based on this part You can further obtain the file information , And proceed to the next stage
Part Class method as follows :

@MultipartConfig
@WebServlet("/upload")
public class UpLoadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Part part= req.getPart("MyImage");
System.out.println(part.getSubmittedFileName());
System.out.println(part.getContentType());
System.out.println(part.getSize());
part.write("e:/ Drawing board /aaa.jpg");
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write(" Upload successful ");
}
}
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="MyImage">
<input type="submit" value=" Submit ">
</form>
</body>
边栏推荐
- leetcode-54. Spiral matrix JS
- Keep an IT training diary 067- good people are grateful, bad people are right
- h t fad fdads
- 5-5配置Mysql复制 基于日志点的复制
- 深入理解 Go Modules 的 go.mod 与 go.sum
- The C Programming Language(第 2 版) 笔记 / 7 输入与输出 / 7.8 其它函数
- 《安富莱嵌入式周报》第268期:2022.05.30--2022.06.05
- [browser principle] variable promotion
- Browsercontext class of puppeter
- Servlet API
猜你喜欢

关于组件传值

Analysis on the development status and direction of China's cultural tourism real estate industry in 2021: the average transaction price has increased, and cultural tourism projects continue to innova

acwing 802. Interval sum (discretization)

统计机器学习代码合集

Kill program errors in the cradle with spotbugs

<山东大学项目实训>渲染引擎系统(三)

acwing 800. Target and of array elements

generate pivot data 0

Thread pool execution process

Axure RP 9 for MAC (interactive product prototyping tool) Chinese version
随机推荐
puppeteer入门之 BrowserContext 类
Acwing high precision multiplication
34-【go】Golang channel知识点
Acwing794 high precision Division
acwing 2816. Judgement subsequence
What is fintech? How fintech can help small businesses succeed
std::set compare
MongoDB系列之SQL和NoSQL的区别
深入理解 Go Modules 的 go.mod 與 go.sum
Global and Chinese market of vascular prostheses 2022-2028: Research Report on technology, participants, trends, market size and share
d的sha6转大整
<山东大学项目实训>渲染引擎系统(三)
34- [go] golang channel knowledge points
[tool recommendation] personal local markdown knowledge map software
The C Programming Language(第 2 版) 笔记 / 8 UNIX 系统接口 / 8.3 open、creat、close、unlink
面试:‘==‘与equals()之间的区别
MySQL - server configuration related problems
The C Programming Language(第 2 版) 笔记 / 8 UNIX 系统接口 / 8.2 低级 I/O(read 和 write)
The market share of packaged drinking water has been the first for eight consecutive years. How does this brand DTC continue to grow?
Sum of acwing796 submatrix
