What’s a cookie?
The Chinese translation of cookie is the meaning of cookie, sweet cake. Cookies are actually some data information of the type”small text file“, stored in a text file on your computer.
What are cookies for?
Let’s imagine a scenario, when we open a website, if this website we once logged in, then when we open the website again, we find that we don’t need to log in again, but directly into the home page. For example, bilibili, csdn and other sites.
How does this work? It’s actually the fact that the tourer saves our cookies, which record some information, and of course, these cookies are created by the server and returned to the tourer. The browser only saves them. The following shows the cookie saved by the bilibili website.
Representation of Cookies
In general, cookies are represented as key-value pairs (key-value), for example, name=jack, which means that the name of the cookie is name and the value carried by the cookie is jack.
Components of a Cookie
Below I wrote my own simple Servlet to set cookies, we excursion packet capture to view. Then analyze
The following is an explanation of the commonly used attributes in cookies.
- Name: this is the name of the cookie
- Value: this is the value of the cooke
- Path: This defines the directory on the Web site where the cookie can be accessed.
- Expires: This value indicates the expiration time of the cookie, that is, the valid value, the cookie is valid until this value.
- Size: This indicates the size of the cookie.
For a complete overview of all cookie attributes, please refer to theBaidu Knowledge: cookie
HTTP transfer of cookies
We’re still going to look at it by grabbing packets. First see how the cookie is represented in the HTTP request.
HTTP request
When we sent the HTTP request, we found that the excursor carried all of our cookies(Note: the excursion will only carry cookies that contain the value of the path in this cookie in the currently requested url)and are represented as key:value. Multiple cookies are separated by ;.
Let’s look at how the cookie is represented in the HTTP response.
HTTP response
I set 2 cookies at the server, which are returned to the excursion. By grabbing the packets, we found that the cookie is represented in the HTTP response as, Set-Cookie: cookie name, cookie value. If there is more than one cookie, then more than one Set-Cookie is used for representation in the HTTP response.
Cookie Life Cycle
There are 2 types of storage for cookies, one is session and one is persistent.
- Session: If the cookie is session, then the cookie will only be stored in the client’s memory and will expire when we close the client.
- Persistence: If a cookie is persistent, the cookie is stored on the user’s hard disk until the end of its lifetime or until the user voluntarily destroys it.
Cookie we can set, we can set the validity of the cookie manually, when to create, when to destroy.
Common Ways Cookies Are Used
Below, I explain the methods of the Cookie object in java
- new Cookie(String name, String value): create a Cookie object, must pass the name of the cookie and the value of the cookie
- getValue(): get the value saved by the cookie
- getName(): get the name of the cookie
- setMaxAge(int expiry): set the expiration date of the cookie, default is -1. If you set a negative number, it means the cookie will be deleted when the client is closed. 0 means it will be deleted immediately. Positive number means the expiration time in seconds.
- setPath(String uri): set the scope of the cookie
HttpServletRequest and HttpServletResponse common methods of manipulating cookies
- response.addCookie(Cookie cookie): the cookie to the client for storage
- resquest.getCookies(): get all the cookie objects passed by the customer service terminal
Examples of Cookie Applications
We use cookies to realize a function, that is, when the user logged in successfully, we will automatically fill in the username and password at the next login. This function we use cookies and jsp page to complete (with html page can also be, but to use javascript, a bit of trouble, so the use of jsp for demonstration )
We start by writing a simple jsp page, which is a login page
JSP page
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title> Login </title>
</head>
<body>
<form action="${pageContext.request.contextPath}/main" method="post">
User name: <input type="text" name="username" value="<%=request.getAttribute("username")%>"><br/>
password: <input type="password" name="password" value="<%=request.getAttribute("password")%>"><br/>
<input type="submit" value=" login ">
</form>
</body>
</html>
Request forwarding page, we are forwarding to the jsp page by accessing the Servlet, not directly.
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/cookieLogin")
public class CookieLogin extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Set the default value
request.setAttribute("username","");
request.setAttribute("password","");
//get all cookies
Cookie[] cookies = request.getCookies();
// Iterate over all cookies
for (Cookie cookie : cookies) {
// Get the cookie storing the username and password and store it in the request field.
if ("username".equals(cookie.getName())){
String value = cookie.getValue();
request.setAttribute("username",value);
}
if("password".equals(cookie.getName())){
String value = cookie.getValue();
request.setAttribute("password",value);
}
}
//Forward to the login.jsp page
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
Home page after successful login
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/main")
public class MainServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Set the response type
response.setContentType("text/html;charset=utf-8");
//get username and password
String username = request.getParameter("username");
String password = request.getParameter("password");
//Judge whether the login is successful or not
if ("root".equals(username) && "root".equals(password)) {
//Writing cookies
Cookie usernameCookie = new Cookie("username", username);
Cookie passwordCookie = new Cookie("password", password);
//Set the validity time, I here set 3 days validity
usernameCookie.setMaxAge(60 * 60 * 24 * 3);
passwordCookie.setMaxAge(60 * 60 * 24 * 3);
//Deposited in the client
response.addCookie(usernameCookie);
response.addCookie(passwordCookie);
// Return to Tips
response.getWriter().write("<h1> Login success ~~~~</h1>");
}else {
response.getWriter().write("<h1> Login failed.... </h1>");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
Let’s test it out by first visitinghttp://localhost:8080/cs/cookieLogin, the virtual path we set up here is cs, and here is the page that shows up when we visit cookieLogin. It turns out that there is indeed no autofill, because we are not logged in yet. There is no username and password cookie stored in the browser.
Enter the correct account number and password to log in. That is, the account number and password are entered into root, the page shows login success
Here’s how we can see if the excursion stores a cookie for username and password
The excursion does store the cookie, no problem, next, we revisit the login page after closing the excursion.
As soon as we visited the login page, the username and password were automatically filled in, successfully implementing the functionality
summarize
Cookie is some data, used to store the information returned to the customer service side of the server, the client to save. In the next visit to the site, the client will save the cookie together with the server, the server and then use the cookie to carry out some operations. The use of cookies we can realize automatic login, save visit history, identity verification and other functions.