如何在JSP中設定Cookie?
使用JSP設定Cookie包含三個步驟:
步驟1:建立Cookie物件
使用Cookie建構函式,傳入Cookie名稱和Cookie值,兩者都是字串。
Cookie cookie = new Cookie("key","value");請記住,名稱和值都不應包含空格或以下任何字元:
[ ] ( ) = , " / ? @ : ;
步驟2:設定最大期限
使用**setMaxAge**指定Cookie的有效時間(以秒為單位)。以下程式碼將設定一個有效期為24小時的Cookie。
cookie.setMaxAge(60*60*24);
步驟3:將Cookie傳送到HTTP響應頭
使用**response.addCookie**在HTTP響應頭中新增Cookie,如下所示:
response.addCookie(cookie);
示例
<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
// Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName );
%>
<html>
<head>
<title>Setting Cookies</title>
</head>
<body>
<center>
<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>讓我們將上述程式碼放在**main.jsp**檔案中,並在下面的HTML頁面中使用它:
<html> <body> <form action = "main.jsp" method = "GET"> First Name: <input type = "text" name = "first_name"> <br /> Last Name: <input type = "text" name = "last_name" /> <input type = "submit" value = "Submit" /> </form> </body> </html>
將上述HTML內容儲存在名為**hello.jsp**的檔案中,並將**hello.jsp**和**main.jsp**放在**<Tomcat安裝目錄>/webapps/ROOT**目錄下。當您訪問 **_https://:8080/hello.jsp_**時,以下是上述表單的實際輸出。
輸出

嘗試輸入名字和姓氏,然後單擊提交按鈕。這將在螢幕上顯示名字和姓氏,並設定兩個Cookie:**firstName**和**lastName**。下次單擊提交按鈕時,這些Cookie將被傳回伺服器。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP