JSP 中的 Cookie 示例
什么是 Cookies?
- Cookie 是存储在客户端机器上的文本文件。
- 它们用于跟踪各种目的的信息。
- 它使用 servlet 技术支持 HTTP cookies
- 这些 cookie 是在 HTTP 标头中设置的。
- 如果浏览器配置为存储 cookie,它将保留信息直到到期日。
JSP 中的 Cookie 类型
- 持久性 Cookie: 持久性 cookie 会在您的设备上存储一段时间,帮助网站记住您的偏好和登录详细信息。
- 非持久性 Cookie: 非持久性 cookie 是临时的,一旦您关闭浏览器就会被删除,主要用于会话跟踪。
JSP Cookies 方法
以下是 cookies 方法:
-
公共无效setDomain(字符串域)
此 JSP 设置 cookie 用于设置 cookie 适用的域
-
公共字符串获取域()
此 JSP get cookie 用于获取 cookie 适用的域
-
公共无效setMaxAge(int expiry)
它设置了 Cookie 过期的最大时间
-
公共 intgetMaxAge()
返回 JSP 中 cookie 的最大使用期限
-
公共字符串获取名称()
返回 cookie 的名称
-
公共无效setValue(字符串值)
设置与 cookie 关联的值
-
公共字符串获取值()
获取与 cookie 关联的值
-
公共无效setPath(字符串路径)
JSP 中的这个设置 cookie 指定了 cookie 适用的路径
-
公共字符串 getPath()
获取 cookie 适用的路径
-
公共无效setSecure(布尔标志)
它是否应该通过加密连接发送。
-
公共无效设置注释(字符串cmt)
它描述了 cookie 的用途
-
公共字符串获取评论()
它返回已经描述的 cookie 注释。
如何在 JSP 中处理 Cookie
- 创建 cookie 对象
- 设置最大年龄
- 在 HTTP 响应标头中发送 cookie
例如:
在这个 JSP cookies 示例中,我们将学习如何在 JSP 中调用 cookie 构造函数,创建用户名和电子邮件的 cookie,并将 10 小时的期限添加到 cookie 中,并尝试获取 action_cookie.jsp 中的变量名称
Action_cookie.jsp。
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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=ISO-8859-1"> <title>Guru Cookie</title> </head> <body> <form action="action_cookie_main.jsp" method="GET"> Username: <input type="text" name="username"> <br /> Email: <input type="text" name="email" /> <input type="submit" value="Submit" /> </form> </body> </html>
动作_cookie_main.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <% Cookie username = new Cookie("username", request.getParameter("username")); Cookie email = new Cookie("email", request.getParameter("email")); username.setMaxAge(60*60*10); email.setMaxAge(60*60*10); // Add both the cookies in the response header. response.addCookie( username ); response.addCookie( email ); %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Guru Cookie JSP</title> </head> <body> <b>Username:</b> <%= request.getParameter("username")%> <b>Email:</b> <%= request.getParameter("email")%> </body> </html>
代码说明
动作_cookie.jsp
代码行10-15: 这里我们采用必须在 action_cookie_main.jsp 中处理的表单。此外,我们采用两个字段“用户名”和“电子邮件”,必须通过提交按钮从用户那里获取输入。
动作_cookie_main.jsp
代码行6-9: 使用 request.getParameter 创建“用户名”和“电子邮件”两个 cookie 对象。
代码行12-13: 这里我们为这两种 cookie 添加年龄,创建时间为 10 小时,即 cookie 将在该年龄内过期。
代码行16-17: 在用户名和电子邮件的会话中添加 cookie,这两个 cookie 可以在 getParameter() 请求时获取。
输出
执行上述代码时,您将获得以下输出:
当我们执行 action_cookie.jsp 时,我们会得到两个字段 username 和 email,它会接受用户输入,然后我们点击提交按钮。我们从 action_cookie_main.jsp 获得输出,其中变量存储在客户端的 cookies JSP 中。