1. Conversation concept
Session: A series of requests and corresponding processes that occur continuously between a browser client and a web server. A session contains multiple requests and responses.
Problems to be solved by sessions: During the session between the browser and the server, each user will inevitably generate some data. The program needs to find a way to save this data for each user.
What sessions do: Share data across multiple requests within the scope of a session.
Conversation mode:
- Client: Cookie
- Server: Session
2. Cookie introduction
Cookie is a client-side technology, and the program returns each user’s data to the user’s respective browser in the form of a cookie. When the current user accesses the same web resource again, they will access it with their own data. In this way, the web resources handle the user’s own data.
1. Cookie usage steps:
① Create Cookie object and bind data
new Cookie(String name, String value)
②Send Cookie object
response.addCookie(Cookie cookie)
③ Get the Cookie object and retrieve the data
Cookie[] cookie = request.getCookies()
Note: The return value of cookie is an array.
2. Cookie implementation principle
Based on the response header set-cookie and the request header cookie, the web server sends the cookie information to the browser by adding the cookie response header field to the HTTP corresponding message, and the browser returns the cookie by adding the cookie request header field to the HTTP request message. to the web server.
3. Cookie usage details
① Multiple Cookies
You can send multiple Cookies at one time, create multiple Cookie objects, and use response to call the addCookie method multiple times to send Cookies.
② Cookie storage period
Close the browser by default and the cookie data will be destroyed, but you can set the cookie to store it persistently, setMaxAge(int seconds), the parameters are as follows:
丶Positive number: Write the cookie to the hard disk file. The numerical value indicates the survival time, in seconds.
丶Negative number: Default value. Destroyed when closed.
丶Zero: Delete cookie data.
③ Store Chinese
Before Tomcat8, Chinese data could not be stored in cookies, and Chinese data needed to be transcoded and URLs used. It is allowed after Tomcat8, but special data is not supported. It is recommended to use URL encoding to store and URL decoding to parse.
4. Cookie sharing
①The same Tomcat
Cookies for multiple web projects deployed in the same tomcat server can be shared. By default, it cannot be shared, but the cookie acquisition range can be set through setPath (String path). By default, it is the current virtual directory. If sharing is required, it can be set to “/”, which is the current server.
②Different Tomcat
setDomain(String path): If the settings and domain name are the same, cookies can be shared between multiple Tomcats. For example: setDomain(“.baidu.com”), the cookies in tieba.baidu.com can also be shared.
Note: A domain name can only store up to 20 cookies
3. Save the user’s last access time (code)
Create a new cookie.com.hbnu package and create a servlet
package com.hbnu.cookie; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; @WebServlet("/cookieServlet1") public class CookieServlet1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1. Solve Chinese garbled characters resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html; charset=utf-8"); //4. Get the cookie and determine whether it is our cookie Cookie[] cookies = req.getCookies(); if (cookies != null){ //4.1 If it is not empty, it means that it has been visited // 5. If there is a cookie of our visitedTime in the cookie, execute it for (Cookie cookie : cookies) { //Assign each value of cookies to cookie if (cookie.getName().equals("visitedTime")) { //5.1 If the condition is true, it means the user logged in last time /*6. Get cookies What we get at this time is our cookie, which stores the system time. Because it is a string type, it is converted to long. And it is a timestamp in milliseconds, which needs to be converted into a date and formatted into the form you are used to. String value = cookie.getValue();*/ long time = Long.parseLong(cookie.getValue()); //Get the time when the user last visited this website Date date = new Date(time); //Convert timestamp to date //format SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E"); resp.getWriter().println("The last time you visited this website was: " + simpleDateFormat.format(date)); } //8. Judgment output if (cookie.getName().equals("username")) { resp.getWriter().println("</br>Your username is: " + cookie.getValue()); } } }else { //4.2 Otherwise resp.getWriter().println("This is your first time visiting this website..."); } //2. Create our cookie and bind the current system time of the data to the cookie. Cookie cookie = new Cookie("visitedTime", System.currentTimeMillis() + ""); //7. Save multiple cookies Cookie cookie1 = new Cookie("username","fallen leaves"); //3. Return the created cookie to the browser client resp.addCookie(cookie); //7.1. Remember that the newly created cookie is also returned to the browser. resp.addCookie(cookie1); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
Start, access this servlet and view it with f12