如何在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