当前位置:网站首页>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");
}
}
边栏推荐
猜你喜欢

Druid监控统计数据源

POI导出excel,按照父子节点进行分级显示

Cookie&Session

Ctfshow blasting WP

XXL job User Guide

The 'mental (tiring) process' of building kubernetes/kubesphere environment with kubekey
![[us match preparation] complete introduction to word editing formula](/img/e4/5ef19d52cc4ece518e79bf10667ef4.jpg)
[us match preparation] complete introduction to word editing formula
![Lavaweb [first understanding the solution of subsequent problems]](/img/8a/08cb2736c2c198d926dbe00c004c3f.png)
Lavaweb [first understanding the solution of subsequent problems]
![[exsi] transfer files between hosts](/img/c3/128b72aca6e030b2d4be2b6bddbc43.png)
[exsi] transfer files between hosts

How do spark tasks of 10W workers run? (Distributed Computing)
随机推荐
Analyze datahub, a new generation metadata platform of 4.7K star
POI exports excel and displays hierarchically according to parent-child nodes
Subnet division (10)
So easy 将程序部署到服务器
JS日常开发小技巧(持续更新)
[applet project development -- JD mall] uni app commodity classification page (first)
HTB-Lame
性能测试常见面试题
POI导出excel,按照父子节点进行分级显示
The shell script uses two bars to receive external parameters
Huawei operator level router configuration example | BGP VPLS configuration example
Introduction to core functions of webrtc -- an article on understanding SDP PlanB unifiedplan (migrating from PlanB to unifiedplan)
So easy deploy program to server
Common interview questions for performance test
打包iso文件的话,怎样使用hybrid格式输出?isohybrid:command not found
Hal library operation STM32 serial port
Introduction to ieda right click source file menu
EtherCAT原理概述
multiple linear regression
ctfshow爆破wp