Cookie s and Ession
1. Session Technology
1.1 Sessions
A session contains multiple requests and responses.
Session: The first time a browser sends a request to a server resource, a session is established until one of the parties disconnects.
1.2 Functions
Share data between multiple requests within a single session.
1.3 Mode
- Client Session Technology: Cookie
- Server-side session technology: Session
2. Cookie
2.1 Overview
Client Session Technology, Save Data to Client
2.2 Steps to use
-
Create a cookie object to bind data.
new Cookie(String name, String value)
-
Send cookie object
response.addCookie(Cookie cookie)
-
Get Cookie s, Get Data
Cookie[] request.getCookies()
@WebServlet("/cookieDemo1") public class CookieDemo1 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. Create a cookie object Cookie cookie = new Cookie("msg", "hello"); //2. Send cookie s response.addCookie(cookie); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } } @WebServlet("/cookieDemo2") public class CookieDemo2 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //3. Get Cookie s Cookie[] cookies = request.getCookies(); //Get data, traverse Cookies if (cookies != null) { for (Cookie c : cookies) { String name = c.getName(); String value = c.getValue(); System.out.println(name+":"+value); } } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
2.3 Implementation Principles
Based on response header set-cookie and request header cookie implementation.
2.4 cookie details (highlights)
-
Can't you send more than one cookie at a time?
Yes,
You can create multiple objects and send a cookie using the response call to the addCookie method multiple times.
-
How long do cookie s stay in the browser?
-
By default, Cookie data is destroyed when the browser is closed.
-
Persistent storage:
setMaxAge(int seconds)
1. **Positive number: will cookie The data is written to a file on the hard disk. Persist storage. cookie Survival time.** 2. **Negative number: default** 3. **Zero: Delete cookie information**
-
-
Can cookie s be saved in Chinese?
Chinese data cannot be stored directly in cookie s until tomcat8
After tomcat8, cookie s support Chinese data.
-
Scope of cookie sharing?
1. If there are multiple web projects deployed in the same tomcat server, can cookie s be shared among these web projects?
Cookies cannot be shared by default
setPath(String path): Sets the scope for cookie s. By default, set the current virtual directory
2. cookie sharing between different tomcat services?setDomain(String path): If the primary domain name is the same, then between servers cookie Can be shared.
setDomain(".baidu.com"), then cookie s in tieba.baidu.com and news.baidu.com can be shared.
-
What are the features and functions of cookie s?
- Cookies store data in client browsers
- Browsers have limits on the size of a single cookie (4kb) and on the total number of cookies under the same domain name (20)
Effect:
- Cookies are typically used to store small amounts of less sensitive data.
- Complete the server's identification of the client without logging on.
- Cookies store data in client browsers
3. cookie case: remember last visit time
-
Requirements:
1. Visit a servlet, if it is your first visit, then prompt: Hello, welcome to your first visit.
2. If it is not your first visit, then Tip: Welcome back, the last time you visited was: Show time string. -
Analysis:
1. Cookies can be used to achieve this
2. The servlet on the server determines if there is a cookie named lastTime
1. Yes: It's not your first visit
1. Response data: Welcome back, your last visit was 11:50:51 June 6, 2021
2. Write back cookie:lastTime=6 June 2021 11:50:51
2. No: First visit
1. Response data: Hello, welcome to your first visit
2. Write back cookie:lastTime=11:50:51 June 10, 2018
/** The servlet on the server determines if there is a cookie named lastTime 1. Yes: not the first visit 1. Response Data: Welcome back, your last visit was 11:50:51 June 6, 2021 2. Write back cookie:lastTime=11:50:51 June 6, 2021 2. No: First visit 1. Response data: Hello, welcome to your first visit 2. Write back cookie:lastTime=11:50:51 June 10, 2018 */ @WebServlet("/cookieTest") public class CookieTest extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Set the data format and encoding of the message body of the response response.setContentType("text/html;charset=utf-8"); //1. Get all cookies Cookie[] cookies = request.getCookies(); boolean flag = false;//No cookie is lastTime //2. Traverse the cookie array if (cookies != null && cookies.length > 0) { for (Cookie c :cookies) { //3. Get the name of the cookie String name = c.getName(); //4. Determine if the name is: lastTime if ("lastTime".equals(name)) { //This cookie is available, not the first time you visit it flag = true;//Cookies with lastTime //Set cookie value //Get the string of the current time, reset the value of the cookie, and resend the cookie Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss"); String str_format = simpleDateFormat.format(date); System.out.println("Before encoding:"+str_format); //URL encoding str_format = URLEncoder.encode(str_format,"utf-8"); System.out.println("After encoding:"+str_format); c.setValue(str_format); //Set cookie lifetime c.setMaxAge(60*60*24*30);//One month //Resend cookie s response.addCookie(c); //Response data //Get cookie value, time String value = c.getValue(); System.out.println("Before decoding:"+value); //URL Decoding value = URLDecoder.decode(value,"utf-8"); System.out.println("After decoding:"+value); response.getWriter().write("<h1>Welcome back, your last visit was:"+value+"</h1>"); break; } } } if (cookies == null || cookies.length == 0 || flag == false) { //No, first visit //Set Cookie value //Get the string of the current time, reset the value of the cookie, and resend the cookie Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss"); String str_format = simpleDateFormat.format(date); System.out.println("Before encoding:"+str_format); //URL encoding str_format = URLEncoder.encode(str_format,"utf-8"); System.out.println("After encoding:"+str_format); Cookie cookie = new Cookie("lastTime", str_format); cookie.setValue(str_format); //Set cookie lifetime cookie.setMaxAge(60 * 60 * 24 * 30);//One month response.addCookie(cookie); response.getWriter().write("<h1>Hello, welcome to your first visit</h1>"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
4.Session
4.1 Concepts
Server-side session technology, which shares data between multiple requests for a second session and stores the data in server-side objects. HttpSession
4.3 Getting Started
-
Get the session object:
HttpSession session = request.getSession();
-
Using the HttpSession object:
Object getAttribute(String name)
void setAttribute(String name, Object value)
void removeAttribute(String name)
4.4 Principle
session implementation is Cookie dependent
4.5 Details
-
When the client shuts down, the server does not shut down. Is it the same session to get two sessions?
By default. No
If the same is required, you can create a cookie with the JSESSIONID key to set the maximum lifetime for the cookie to persist.
//Expect session s to be the same when the client shuts down Cookie cookie = new Cookie("JSESSIONID",session.getId()); cookie.setMaxAge(60*60); response.addCookie(cookie);
-
Client does not shut down. After server shuts down, do you get the same session twice?
Not the same, but make sure the data is not lost.
org.apache.catalina.session.StandardSessionFacade@1bb64cbb org.apache.catalina.session.StandardSessionFacade@6bd8cb0e
Passivation of session:
Serialize the session object to the hard disk before the server shuts down normally.
Activation of session:
Convert the session file into an in-memory session object after the server starts up normally.
-
When was session destroyed?
-
Server shutdown
-
The session object calls invalidate().
-
session default expiration time of 30 minutes
Selective Configuration Modification
<session-config> <session-timeout>30</session-timeout> </session-config>
-
4.6 Features
- Session stores data for multiple requests for a session and is server-side.
- Sessions can store data of any type and size.
The difference between session and cookie:
-
session stores data on the server side, cookie s store data on the client side
-
session has no data size limit, cookies have.
-
session data is secure, cookies are not.
<session-config> <session-timeout>30</session-timeout> </session-config> ```
4.6 Features
- Session stores data for multiple requests for a session and is server-side.
- Sessions can store data of any type and size.
The difference between session and cookie:
- session stores data on the server side, cookie s store data on the client side
- session has no data size limit, cookies have.
- session data is secure, cookies are not.