Hello everyone! When I first started learning Java programming, I was particularly curious about how to track user states and manage sessions in web applications. Later, I discovered that Java’s Cookie library acts like a helpful little steward, assisting us in managing HTTP cookies for user state tracking and session management. Today, I will provide a detailed discussion on this topic.
1. Understanding Java’s Cookie Library
At first, I was quite confused by Java’s Cookie library, feeling that it was rather complex. In fact, the Java Cookie library is like little tags given to users; the Cookie class can store some user-related information on the client side (usually in the browser). When the user visits the server again, these tags can be brought along, allowing the server to know some state information about the user, similar to how a supermarket gives us a membership card, which allows them to know our purchase history each time we shop.
The Java Cookie library is primarily contained in the <span>javax.servlet.http</span>
package, specifically in the <span>Cookie</span>
class. This class can create, read, and modify cookies.
Tip: Cookies are stored on the client side, so do not store sensitive information in cookies, just like you wouldn’t write your bank card password on a membership card, as it poses a security risk.
2. Creating and Sending Cookies
(1) Concept Explanation
Creating and sending a cookie means that the server generates a cookie containing specific information and then sends this cookie to the client through the response header, allowing the client to save it, just like a supermarket issuing us a membership card and handing it to us.
(2) Code Example
1import javax.servlet.ServletException;
2import javax.servlet.annotation.WebServlet;
3import javax.servlet.http.Cookie;
4import javax.servlet.http.HttpServlet;
5import javax.servlet.http.HttpServletRequest;
6import javax.servlet.http.HttpServletResponse;
7import java.io.IOException;
8
9@WebServlet("/createCookie")
10public class CreateCookieServlet extends HttpServlet {
11 @Override
12 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
13 // Create a cookie with the name username and value John
14 Cookie cookie = new Cookie("username", "John");
15 // Set the cookie's validity period to 1 day (in seconds)
16 cookie.setMaxAge(86400);
17 // Add the cookie to the response
18 response.addCookie(cookie);
19 response.getWriter().println("Cookie has been created and sent");
20 }
21}
(3) Explanation of the Running Result
This code defines a servlet that creates a cookie named <span>username</span>
with the value <span>John</span>
when the client accesses the URL <span>/createCookie</span>
. It sets the cookie’s validity period to 1 day, adds the cookie to the response, and sends it to the client. After receiving the response, the client will save this cookie. Finally, the server will return “Cookie has been created and sent” to the client.
(4) Practical Application Scenario
In a user login system, when a user successfully logs in, the server can create a cookie containing the user ID and send it to the client. The next time the user visits, the server can identify the user based on this cookie.
3. Reading Cookies
(1) Concept Explanation
Reading a cookie means that the server retrieves the previously sent cookie information from the client’s request, similar to how a supermarket reads our purchase records based on our membership card.
(2) Code Example
1import javax.servlet.ServletException;
2import javax.servlet.annotation.WebServlet;
3import javax.servlet.http.Cookie;
4import javax.servlet.http.HttpServlet;
5import javax.servlet.http.HttpServletRequest;
6import javax.servlet.http.HttpServletResponse;
7import java.io.IOException;
8
9@WebServlet("/readCookie")
10public class ReadCookieServlet extends HttpServlet {
11 @Override
12 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
13 // Get all cookies sent by the client
14 Cookie[] cookies = request.getCookies();
15 if (cookies != null) {
16 for (Cookie cookie : cookies) {
17 if (cookie.getName().equals("username")) {
18 // Find the cookie named username and print its value
19 response.getWriter().println("Username: " + cookie.getValue());
20 }
21 }
22 } else {
23 response.getWriter().println("No cookies found");
24 }
25 }
26}
(3) Explanation of the Running Result
This code defines a servlet that retrieves all cookies from the request when the client accesses the URL <span>/readCookie</span>
. If cookies exist, it iterates through them to find the cookie named <span>username</span>
and prints its value. If no cookies are found, it outputs “No cookies found”.
(4) Precautions
When reading cookies, be aware that cookie names may be duplicated, so handle them according to the actual situation, just like a supermarket may have duplicate membership cards that need to be distinguished by other information.
4. Modifying and Deleting Cookies
(1) Concept Explanation
Modifying a cookie means updating its value or validity period, while deleting a cookie means instructing the client to remove a specific cookie, similar to how a supermarket updates membership card information or cancels a membership.
(2) Code Example
1import javax.servlet.ServletException;
2import javax.servlet.annotation.WebServlet;
3import javax.servlet.http.Cookie;
4import javax.servlet.http.HttpServlet;
5import javax.servlet.http.HttpServletRequest;
6import javax.servlet.http.HttpServletResponse;
7import java.io.IOException;
8
9@WebServlet("/modifyOrDeleteCookie")
10public class ModifyOrDeleteCookieServlet extends HttpServlet {
11 @Override
12 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
13 // Modify a cookie
14 Cookie[] cookies = request.getCookies();
15 if (cookies != null) {
16 for (Cookie cookie : cookies) {
17 if (cookie.getName().equals("username")) {
18 // Modify the cookie's value
19 cookie.setValue("Tom");
20 // Set a new validity period
21 cookie.setMaxAge(3600);
22 // Add the modified cookie to the response
23 response.addCookie(cookie);
24 response.getWriter().println("Cookie has been modified");
25 }
26 }
27 }
28
29 // Delete a cookie
30 Cookie cookieToDelete = new Cookie("username", null);
31 cookieToDelete.setMaxAge(0);
32 response.addCookie(cookieToDelete);
33 response.getWriter().println("Cookie has been deleted");
34 }
35}
(3) Explanation of the Running Result
This code defines a servlet that attempts to modify the value of the cookie named <span>username</span>
to <span>Tom</span>
and sets a new validity period of 1 hour when the client accesses the URL <span>/modifyOrDeleteCookie</span>
. It then creates a cookie with the same name, sets its value to <span>null</span>
, and its validity period to 0, adding it to the response so that the client will delete this cookie. Finally, it outputs “Cookie has been modified” and “Cookie has been deleted”.
5. Exercises
- Write a Java program using the Cookie library to implement a simple user visit count tracking feature that records and displays the visit count each time the user accesses the page.
- Consider how you would design code to implement a shopping cart system using the Java Cookie library to save user shopping cart information. Please describe your implementation ideas and write the relevant code framework.
That’s all for today’s Java learning content! Remember to practice more, and feel free to reach out to me in the comments if you have any questions. Wishing everyone smooth learning and improvement in Java skills!