Java Cookies:如何使用 Cookies 進行 Java Servlet 會話管理
已發表: 2020-08-19
網頁沒有記憶。 用戶從一個頁面到另一個頁面將被網站視為一個全新的訪問者。 會話 cookie 使您正在訪問的網站能夠跟踪您從一個頁面到另一個頁面的移動,這樣您就不會被要求提供您已經提供給該網站的相同信息。
Cookie 允許您快速輕鬆地瀏覽網站的許多頁面,而無需驗證或重新處理您訪問的每個新區域。
但有時在 Java Web 應用程序中,我們應該知道客戶端是誰並相應地處理請求。
例如,購物車應用程序應該知道誰在發送添加商品的請求以及商品必須添加到哪個購物車中,或者誰在發送結賬請求,以便它可以向正確的客戶收取金額。
會話是客戶端和服務器之間的會話狀態,它可以由客戶端和服務器之間的多個請求和響應組成。 由於 HTTP 和 Web 服務器都是無狀態的,因此維護會話的唯一方法是在每個請求和響應中在服務器和客戶端之間傳遞有關會話的一些唯一信息(會話 id)。

現在讓我們在 Eclipse 中創建簡單的動態 Web 項目,它解釋了使用 Cookie 進行 Java Servlet 會話管理。
以下是步驟:
- 創建動態 Web 項目:
CrunchifySessionManagementByCookie
-
crunchify-login.html
:創建應用程序的歡迎頁面 CrunchifyLoginServlet.java
– 負責登錄請求CrunchifyLogoutServlet.java
– 負責註銷請求web.xml
- 部署描述符文件(沒有看到 web.xml?按照本教程)-
CrunchifyLoginSuccessful.jsp
– 成功請求被轉發到LoginSuccess.jsp
,該 cookie 將用於跟踪會話。 另請注意,cookie 超時設置為 60 分鐘。

另一個必須閱讀:
- Spring MVC 示例/教程:Hello World – Spring MVC 3.2.1
- 如何在 Spring MVC 中每 3 秒更新一次 Sparkline Graph(實時更新)
1. crunchify-login.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
< ! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > < html > < head > < meta http - equiv = "Content-Type" content = "text/html; charset=US-ASCII" > < title > Crunchify Login Form - Session Management by Cookies < / title > <style type ="text/css"> body { background-image : url ( 'https://cdn.crunchify.com/bg.png' ) ; } </style> < / head > < body > < div align = "center" > < br > < br > < form action = "CrunchifyLoginServlet" method = "post" > Enter Your Username : < input type = "text" name = "crunchifyUser" > < br > Enter Your Password : < input type = "password" name = "crunchifyPassword" > < br > < br > < br > < input type = "submit" value = "Login" > < / form > < / div > < / body > < / html > |
2. CrunchifyLoginServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
package com . crunchify . tutorials ; import java . io . IOException ; import java . io . PrintWriter ; import javax . servlet . RequestDispatcher ; 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 ; /* * Author: Crunchify.com * */ /** * Servlet implementation class LoginServlet */ @WebServlet ( "/CrunchifyLoginServlet" ) public class CrunchifyLoginServlet extends HttpServlet { private static final long serialVersionUID = 1L ; private final String userID = "CrunchifyUser" ; private final String password = "CrunchifyPassword" ; protected void doPost ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { // get request parameters for userID and password String crunchifyUser = request . getParameter ( "crunchifyUser" ) ; String pwd = request . getParameter ( "crunchifyPassword" ) ; if ( userID . equals ( crunchifyUser ) && password.equals(pwd)) { Cookie crunchifyCookie = new Cookie("crunchifyUser", crunchifyUser); // setting cookie to expiry in 60 mins crunchifyCookie . setMaxAge ( 60 * 60 ) ; response . addCookie ( crunchifyCookie ) ; response . sendRedirect ( "CrunchifyLoginSuccess.jsp" ) ; } else { RequestDispatcher rd = getServletContext ( ) . getRequestDispatcher ( "/crunchify-login.html" ) ; PrintWriter out = response . getWriter ( ) ; out . println ( "<font color=red>Please make sure you enter UserID/Pass as \"CrunchifyUser : CrunchifyPassword\".</font>\n" ) ; rd . include ( request , response ) ; } } } |
3. CrunchifyLogoutServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package com . crunchify . tutorials ; import java . io . IOException ; 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 ; /* * Author: Crunchify.com * */ /** * Servlet implementation class LogoutServlet */ @WebServlet ( "/CrunchifyLogoutServlet" ) public class CrunchifyLogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L ; protected void doPost ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { response . setContentType ( "text/html" ) ; Cookie loginCookie = null ; Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies ! = null ) { for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( "crunchifyUser" ) ) { loginCookie = cookie ; break ; } } } if ( loginCookie ! = null ) { loginCookie . setMaxAge ( 0 ) ; response . addCookie ( loginCookie ) ; } response . sendRedirect ( "crunchify-login.html" ) ; } } |
4.web.xml
1 2 3 4 5 6 7 8 9 10 |
<? xml version = "1.0" encoding = "UTF-8" ?> < web - app xmlns : xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xsi : schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0" > < display - name > CrunchifySessionManagementByCookie < / display - name > < welcome - file - list > < welcome - file > crunchify - login . html < / welcome - file > < / welcome - file - list > < / web - app > |
5. CrunchifyLoginSuccessful.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<% @ page language = "java" contentType = "text/html; charset=US-ASCII" pageEncoding = "US-ASCII" %> < ! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > < html > < head > < meta http - equiv = "Content-Type" content = "text/html; charset=US-ASCII" > < title > Crunchify - Login Successful - Session management by Cookies < / title > <style type ="text/css"> body { background-image : url ( 'https://cdn.crunchify.com/bg.png' ) ; } </style> < / head > < body > < div align = "center" > < br > < br > <% String userName = null ; Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies ! = null ) { for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( "crunchifyUser" ) ) userName = cookie . getValue ( ) ; } } if ( userName == null ) response . sendRedirect ( "crunchify-login.html" ) ; %> < h3 > Hi <%= userName %> , Login successful . < / h3 > < br > < form action = "CrunchifyLogoutServlet" method = "post" > < input type = "submit" value = "Logout" > < / form > < / div > < / body > < / html > |
現在讓我們運行這個例子:
-
CrunchifySessionManagementByCookie
項目部署到 Tomcat 並運行 Tomcat。

- 將您的瀏覽器 URL 指向 http://localhost:8080/CrunchifySessionManagementByCookie/crunchify-login.html

- 成功頁面

- 登錄頁面失敗

現在如何檢查您的 Cookie 是否設置正確。

嘗試下載任何Cookie Manager Extension
,您應該會在瀏覽器中看到Cookie
,如下所示。

如果您在運行 Servlet Cookie 管理代碼時遇到任何問題,請告訴我。