1, Basic concepts
Session: a session contains multiple requests and responses
One session: the browser sends a request to the server resource for the first time, and the session is established until one party disconnects (the browser or client is closed)
Function: share data between multiple requests within a session
Method:
- Client session Technology: cookies
- Server side Session Technology: Session
2, Cookie s
1. Use steps
- Create Cookie object and bind data
- new Cookie(String name, String value)
- Send Cookie object
- response.addCookie(Cookie cookie)
- Get cookies and get data
- Cookie[] request.getCookies()
@WebServlet("/cookiedemo1") public class CookieDemo1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie newcookie = new Cookie("msg","hello"); resp.addCookie(newcookie); Cookie[] cookies = req.getCookies(); for (Cookie cookie : cookies) { System.out.println(cookie.getName()); System.out.println(cookie.getValue()); } } }
2. Principle
Implementation based on response header set cookie and request header cookie
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-hacb7c3c-16366200530009) (C: \ users \ Ken CHY \ appdata \ roaming \ typora \ typora user images \ image-20211107193307912. PNG)]
After sending a request (no cookie related request header) to cookie Demo1 for the first time, there will be a set cookie in the response header: MSG = hello
When sending a request the second time (whether to cookie Demo1 or cookie demo2), the browser will automatically carry the request header cookie:msg=hello
3. cookie details
- Can I send more than one cookie at a time?
- You can create multiple Cookie objects and use response to call addCookie method multiple times
- How long do cookie s stay in the browser?
- By default: when the browser is closed, the cookie data will be automatically destroyed (that is, it will be saved in the browser's memory. When the memory is released when the browser is closed, it will be destroyed)
- Persistent storage: set the life cycle of cookie s through setMaxAge(int seconds)
- Positive number: write the cookie data to the file on the hard disk for persistent storage. Seconds indicates the number of seconds the cookie is alive
- Negative number: the default value is automatically destroyed when the browser is turned off
- 0: delete cookie information
- Can cookie s be saved in Chinese?
- Before Tomcat 8, cookie s cannot store Chinese data directly
- Chinese data needs to be transcoded - generally into URL coding
- After Tomcat 8, cookie s support Chinese data, but do not support special characters. It is recommended to use URL encoding and URL decoding
- Before Tomcat 8, cookie s cannot store Chinese data directly
- cookie sharing problem?
- Suppose multiple web projects are deployed in a Tomcat server, can cookie s be shared in these web projects?
- Cannot be shared by default
- setPath(String path): set the cookie acquisition range. By default, it is set to the current virtual directory. If sharing is required, it can be set to '/' (for example, if the project is localhost:8080/myfirst, the default setting is / myfirst, and if it is set to /, it can be shared with other projects)
- Can cookie s be shared between different Tomcat servers?
- setDomain(String path): if the primary domain name is set to be the same, multiple server home cookies can be shared (for example, setDomain(".baidu.com"), cookies in tieba.baidu.com and news.baidu.com can be shared)
- Suppose multiple web projects are deployed in a Tomcat server, can cookie s be shared in these web projects?
4. Characteristics and functions of cookie s
characteristic
- Cookies store data in the client browser
- The browser limits the size of a single cookie (usually 4kb) and the total number of cookies under a domain name (usually 20)
effect
- Cookies are generally used to store small amounts of less sensitive data
- Complete the server-side identification of the client without logging in (because it is through the database after logging in)
5. Use case
1) Demand
- Visit a Servlet. If it is the first time, you will be prompted: Hello, welcome to visit for the first time
- If it is not your first visit, you will be prompted: Welcome back. Your last visit was: xxx
2) Analysis
- This can be done using cookie s
- Determine whether there is a Cookie named lastTime * * (use equals: cookie.getName().equals("lastTime")) in the Servlet in the server**
- Yes: not the first visit
- Response data: Welcome back. Your last visit was xxx
- Write back cookie: lastTime=xxx
- No: This is the first visit
- Response data: Hello, welcome to visit for the first time
- Write back cookie: lastTime=xxx
- Yes: not the first visit
3) Realize
@WebServlet("/cookieTest") public class CookieTest extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get the current time and format it Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy year MM month dd day hh:mm:ss"); String newTime = formatter.format(date); //url code the time so that the output will not be garbled newTime = URLEncoder.encode(newTime,"utf-8"); //Format the data sent by the response hair response.setContentType("text/html;charset=utf-8"); Cookie[] cookies = request.getCookies(); //No corresponding cookie boolean flag = false; if(cookies != null && cookies.length != 0){ for (Cookie cookie : cookies) { if(cookie.getName().equals("lastTime")){ //There is a corresponding cookie flag = true; //Gets the time of the last visit String lastTime = cookie.getValue(); //Decode time lastTime = URLDecoder.decode(lastTime,"utf-8"); response.getWriter().write("<h1>Welcome back. Your last visit was:" + lastTime + "</h1>"); //Reassign the cookie with the new time after encoding cookie.setValue(newTime); //Set persistence time cookie.setMaxAge(30 * 24 * 60 * 60); response.addCookie(cookie); break; } } } //If there is no corresponding cookie if(cookies == null || cookies.length == 0 || flag == false){ response.getWriter().write("<h1>Hello, welcome to your first visit!</h1>"); Cookie cookie = new Cookie("lastTime",newTime); cookie.setMaxAge(30 * 24 * 60 * 60); response.addCookie(cookie); } } }
3, Introduction to JSP
1. Concept
JSP, namely Java Server Pages, can be understood as a special page, in which both html tags and Java code can be defined
Used to simplify writing
2. Principle
JSP is essentially a Servlet
3. How to define java code
JSP script:
- <% code% >: the defined java code is in the service method. The script can define what can be defined in the service method
- <%! Code% >: the member position of the defined java code in the Java class after jsp conversion
- %% = code% >: the defined java code will be exported to the page (essentially calling the out in the service method), and what the output statement can define, and what the script can define.
4. Built in object of JSP
The built-in object of JSP refers to the object that can be used directly without obtaining and creating in JSP pages
jsp has a total of 9 built-in objects
- request
- response
- out: byte stream output object, which can output data to the page, similar to response.getWriter()
- Before the Tomcat server really responds to the client, it will find the response buffer data first, and then the out buffer data, so the data output by response.getWriter().write() is always before out.write()
4, Session
Save the data in the HttpServlet object on the server side
1. Use steps
Get HttpSession object:
- request.getSession();
Use the HttpSession object:
- Object getAttribute(String name)
- void setAttribute(String name, Object value)
- void removeAttribute(String name)
@WebServlet("/sessiondemo1") public class SessionDemo1 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get session HttpSession session = request.getSession(); //Store data session.setAttribute("name", "cyh"); }
@WebServlet("/sessiondemo2") public class SessionDemo2 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get session HttpSession session = request.getSession(); //get data String name = String.valueOf(session.getAttribute("name")); response.getWriter().write(name); } }
2. Principle
Session is Cookie dependent
When the Session is obtained for the first time, there is no corresponding cookie in the request header. At this time, a new Session object will be created in memory. This object will have a JSESSIONID. In the response header, JSESSIONID will be added to the cookie and returned to the browser (in the response header: set Cookie: JSSEIONID=xxxx)
Then, when the Session does not end, whenever the browser sends a request, it will send this JSESSIONID to the server as a cookie in the request header, so as to ensure that the Session object obtained within the scope of a Session is the same (Cookie: JSESSIONID = XXXX in the request header)
3. Session details
-
When the client is shut down, the server will not be shut down. Are the two sessions the same?
-
Not by default
-
If the requirements are the same, you can create a Cookie with the key JSESSIONID, set the maximum survival time, and persist the Cookie
-
HttpSession httpSession = request.getSession(); Cookie c = new Cookie("JSESSIONID",httpSession.getId()); c.setMaxAge(60 * 60); response.addCookie(c);
-
-
When the client is not shut down and the server is shut down, are the two sessions obtained the same?
- Not the same (because the object is destroyed), but the server will ensure that the data is not lost
- Before the server shuts down normally, the session object will be serialized to the hard disk (passivation of session)
- After the server starts, the session file will be converted into a session object in memory (session activation)
- Deploying a project directly using Tomcat will automatically implement this operation, but it will not be implemented in the IDEA (the IDEA is only used for development, and later projects will not be deployed on it, so it has no impact)
- Not the same (because the object is destroyed), but the server will ensure that the data is not lost
-
Session expiration time?
-
The server is closed (the browser will not be destroyed when it is closed, so that the browser can continue to obtain the previous data after the cookie is persisted)
-
The session object calls invalidate()
-
The default expiration time of the session object is 30 minutes
-
You can modify the default expiration time yourself
-
Modify in the web.xml file
<session-config> <session-timeout>30</session-timeout> </session-config>
-
-
4. Characteristics of Session
- Session is used to store the data of multiple requests of a session, which is stored on the server side
- session can store data of any type and size
5. The difference between Session and Cookie
- session stores data on the server side and cookie s on the browser side
- session can store data of any type and size, and cookie s can only store small data of String type
- session data is secure, and cookie s are relatively insecure
ion-timeout>
```
4. Characteristics of Session
- Session is used to store the data of multiple requests of a session, which is stored on the server side
- session can store data of any type and size
5. The difference between Session and Cookie
- session stores data on the server side and cookie s on the browser side
- session can store data of any type and size, and cookie s can only store small data of String type
- session data is secure, and cookie s are relatively insecure=