当前位置:网站首页>Cookie&Session
Cookie&Session
2022-07-01 03:23:00 【Al_ tair】
Web Develop conversation technology
Hello, everyone , I'm Xiao Sheng , Let me share with you my study Javaweb The notes
Web Develop conversation technology
What is conversation ?
Conversation can be simply understood as : Users open a browser , Click on multiple hyperlinks , Access multiple servers web resources , Then close the browser , The whole process is called a conversation
Two techniques of conversation
Cookie
Concept :Cookie The server saves the user's information on the client , Like login name , Browse history, etc , You can to cookie Way,
cookie Frame diagram

Cookie The role of
- Save the last login time and other information
- Save user name , password , You don't have to log in again for a certain time
- Personalization of the website , For example, customized website services , Content
Read Cookie data
Browser side creation email=1079936135qq.com The data of

Browser transfers to server Cookie data

The server read Cookie data
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie[] cookies = request.getCookies(); if(cookies != null && cookies.length != 0){ for (Cookie coke : cookies) { // cookieName: email cookieValue1079936135 // cookieName: Idea-6463f311 cookieValue6cb7445e-85d8-4a31-a12a-bcdbe5c375d9 // If you read the Chinese name // Can pass URLDecoder.decode(coke.getName(),"utf-8") decode System.out.println("cookieName: " + coke.getName() + " cookieValue" + coke.getValue()); } } }
establish Cookie example

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("cookie Called ");
// establish Cookie object
// Solve the reason why Chinese cannot be stored , Need to carry out url code
String data = URLEncoder.encode(" Niansheng ","UTF-8");
Cookie cookie = new Cookie("username",data);
// take Cookie Send to browser and save
response.addCookie(cookie);
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.write("<h1>Cookie Create success !</h1>");
writer.flush();
writer.close();
}
modify Cookie value

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
String cookieName = "email";
Cookie cookie = CookieUtils.nameToGetCookie(cookieName, cookies);
CookieUtils.IterCookie(cookies);
if(cookie == null){
System.out.println(" There is no the Cookie");
}else{
cookie.setValue("[email protected]");
CookieUtils.IterCookie(cookies);
response.addCookie(cookie);
}
}
// Tool class
public class CookieUtils {
/** * adopt CookieName To get the corresponding Cookie */
public static Cookie nameToGetCookie(String cookieName,Cookie[] cookies){
if(cookieName != null && !cookieName.equals("") && cookies != null && cookies.length != 0){
for (Cookie cookie : cookies) {
if(cookie.getName().equals(cookieName)){
return cookie;
}
}
}
return null;
}
/** * Traverse Cookie, Show Cookie Of name-value */
public static void IterCookie(Cookie[] cookies){
System.out.println();
if(cookies != null && cookies.length != 0){
for (Cookie cookie : cookies) {
System.out.println("cookieName: " + cookie.getName() + " cookieValue: " + cookie.getValue());
}
}
System.out.println();
}
}
cookie Life cycle
Common methods
// Positive numbers , Represents an expiration after a specified number of seconds
// negative , Indicates that the browser is closed Cookie It will be deleted ( The default value is -1)
// 0, Delete immediately Cookie ( Can be used to delete Cookie)
setMaxAge()
Code example
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Create a new Cookie object
Cookie cookie = new Cookie("age","18");
// Set up Cookie Life cycle of 20s
cookie.setMaxAge(20);
// Return to the browser to store 20s
response.addCookie(cookie);
}
cookie Effective path
Cookie Of path Attributes can effectively filter which Cookie Can be sent to the server , Which don't . path Attributes are effectively filtered through the requested address
// Illustrate with examples ( Default setPath:/ Project path )
cookie1.setPath = / Project path
cookie2.setPath = / Project path /aaa
// url Request address : http://ip: port / Project path / resources
cookie1 It will be sent to the server
cookie2 It will not be sent to the server
// url Request address : http://ip: port / Project path /aaa/ resources
cookie1 It will be sent to the server
cookie2 It will be sent to the server
Cookie Notes and details
One Cookie Only one message can be identified , It contains at least one name that identifies the information (NAME) And settings (VALUE)
One WEB Sites can send multiple messages to a browser Cookie, A browser can also store multiple WEB The site provides Cookie
Cookie There is no limit to the total number of , But for each domain name Cookie Quantity and each Cookie There is a limit to the size of ( Different browsers have different restrictions ) , Cookie Not suitable for storing information with large amount of data
Pay attention to Chinese deposit cookie Need to encode and decode
// url code String data = URLEncoder.encode(" Chinese you want to deposit ","UTF-8"); Cookie cookie = new Cookie("username",data); //url decode URLDecoder.decode(cookie data ,"utf-8");
Session
Basic introduction
Concept :Session It's server-side technology , The server creates an exclusive browser for each user at run time session object / aggregate , because session Exclusive for each user browser , So when users visit different pages of the server , From their own Of session Read from / Add data
session The default existence time of the object is 30min
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<!-- Tomcat in web.xml File can be configured with time , Default 30min -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Session The role of
- Put data into Session in , For users to access different pages , Achieve cross page access to data
- Save login user information
- Prevent users from illegally logging in to a page, and so on
session Storage structure diagram
| name (key) | value (value) |
|---|---|
| String type | Object type |
Common methods
// 1. Create and get Session
// The first 1 The next call is to create Session conversation , After that, the call is created and created. Session object
HttpSession hs=request.getSession();
// 2. towards session Add attribute
hs.setAttribute(String name,Object val);
// 3. from session Get an attribute
Object obj=hs.getAttribute(String name);
// 4. from session Delete a property :
hs.removeAttribute(String name);
// 5. Judge whether it has just been created Session
hs.isNew();
// 6. Every Session There are 1 A unique identity Id value , adopt getId() obtain Session Conversation id value (JSESSIONID)
Schematic diagram
JSESSIONID
Used by the server to identify different sessions , Different sessions , The server will create different JSESSIONID

Frame diagram

Example of operation code
Set properties
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
HttpSession session = request.getSession();
session.setAttribute("id","1234956789");
System.out.println(" Property setting complete ");
writer.flush();
writer.close();
}
read attribute
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
HttpSession session = request.getSession();
Object s = session.getAttribute("id");
if(s != null){
System.out.println((String)s);
}else{
System.out.println(" No attribute ");
}
writer.flush();
writer.close();
}
session Life cycle
Session The life cycle of is : client / The maximum interval between two browser requests is , Not the cumulative length of time . That is, when the client accesses its own session,session The life cycle of will start from 0 Start recalculating .( The interval between two requests in the same session )
Bottom : Tomcat Polling session status with a thread , If the idle time of a session exceeds the set maximum , Destroy the session
// Set up Session Timeout for ( In seconds ), Exceeded the specified duration ,Session Will be destroyed
// 1. When the value is positive , Set up Session The timeout period of
// 2. Negative numbers never time out
// 3. If not called setMaxInactiveInterval() To specify the Session Life span of ,Tomcat Will Session The default duration shall prevail ,Session The default timeout is 30 minute , Can be in tomcat Of web.xml Set up ; Be careful Cookie Is the cumulative duration , When time comes, it will be destroyed
public void setMaxInactiveInterval(int interval)
// obtain Session Timeout for
public int getMaxInactiveInterval()
// Let the current Session The session is immediately invalid
public void invalidate()
Classic case
Prevent illegal access to the management page
- login.html Submit the form to LoginCheckServlet.java
- If the validation is successful ( User name is not empty , The password for 666666,), Then enter the management page ManageServelt.java, If the verification is not successful , Jump to error.html page
- If the user has direct access to ManageServet.java , Redirect to login.html
<!-- login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> The user login </title></head>
<body><h1> The user login </h1>
<form action="/session/loginCheck" method="post">
user name :<input type="text" name="username"/><br/><br/>
The secret code :<input type="password" name="password"><br><br/>
<input type="submit" value=" Sign in ">
</form>
</body>
</html>
<!-- error.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> Login failed </h1>
<a href="login.html" style="text-decoration: none"> Click back to log in again </a>
</body>
</html>
// LoginCheckServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username != null && password != null){
if(!"".equals(username) && "666666".equals(password)){
HttpSession session = request.getSession();
session.setAttribute("username",username);
request.getRequestDispatcher("/manageServlet").forward(request,response);
}else{
request.getRequestDispatcher("/error.html").forward(request,response);
}
}else{
response.sendRedirect("/login.html");
}
}
// ManageServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Object username = session.getAttribute("username");
if(username != null){
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.println("<h1> User management page </h1>");
writer.println(" Welcome , Administrators : " + (String)username);
writer.flush();
writer.close();
}else{
response.sendRedirect("/session/login.html");
}
}
边栏推荐
- Chapitre 03 Bar _ Gestion des utilisateurs et des droits
- C语言多线程编程入门学习笔记
- Edge Drawing: A combined real-time edge and segment detector 翻译
- Introduction and installation of Solr
- Nacos
- Huawei operator level router configuration example | BGP VPLS configuration example
- Cloud native annual technology inventory is released! Ride the wind and waves at the right time
- Install vcenter6.7 [vcsa6.7 (vCenter server appliance 6.7)]
- Data exchange JSON
- Druid monitoring statistics source
猜你喜欢

HTB-Lame

Example of Huawei operator level router configuration | example of configuring optionc mode cross domain LDP VPLS

A few lines of transaction codes cost me 160000 yuan

Avalanche problem and the use of sentinel

Hello World generation

彻底解决Lost connection to MySQL server at ‘reading initial communication packet

岭回归和lasso回归

服务器渲染技术jsp

Metadata in NFT
![[small program project development -- Jingdong Mall] the home page commodity floor of uni app](/img/80/20bed20a6ab91e82ad6800b11f2caa.png)
[small program project development -- Jingdong Mall] the home page commodity floor of uni app
随机推荐
Design practice of current limiting components
Finally in promise
Mybati SQL statement printing
串口接收数据方案设计
Summary of problems encountered in debugging positioning and navigation
Data exchange JSON
Huawei operator level router configuration example | BGP VPLS and LDP VPLS interworking example
EtherCAT原理概述
[applet project development -- JD mall] uni app commodity classification page (first)
[machine learning] vectorized computing -- a must on the way of machine learning
How the network is connected: Chapter 2 (Part 2) packet receiving and sending operations between IP and Ethernet
如何校验两个文件内容是否相同
Analyze datahub, a new generation metadata platform of 4.7K star
Redis 教程
Redis tutorial
Detailed list of errors related to twincat3 ads of Beifu
Let's just say I can use thousands of expression packs
Keil5中如何做到 0 Error(s), 0 Warning(s).
打包iso文件的话,怎样使用hybrid格式输出?isohybrid:command not found
数据交换 JSON