11月5日学习日志
今天学习了servlet设置 Cookie。
通过 Servlet 设置 Cookie 包括三个步骤:
(1) 创建一个 Cookie 对象:您可以调用带有 cookie 名称和 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);
实例:
package com.runoob.test; import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; 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; /** * Servlet implementation class HelloServlet */ @WebServlet("/HelloForm") public class HelloForm extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public HelloForm() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 为名字和姓氏创建 Cookie Cookie name = new Cookie("name", URLEncoder.encode(request.getParameter("name"), "UTF-8")); // 中文转码 Cookie url = new Cookie("url", request.getParameter("url")); // 为两个 Cookie 设置过期日期为 24 小时后 name.setMaxAge(60*60*24); url.setMaxAge(60*60*24); // 在响应头中添加两个 Cookie response.addCookie( name ); response.addCookie( url ); // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "设置 Cookie 实例"; String docType = "<!DOCTYPE html>\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>站点名:</b>:" + request.getParameter("name") + "\n</li>" + " <li><b>站点 URL:</b>:" + request.getParameter("url") + "\n</li>" + "</ul>\n" + "</body></html>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
最后尝试下面的 HTML 页面来调用 Servlet。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <form action="/TomcatTest/HelloForm" method="GET"> 站点名 :<input type="text" name="name"> <br /> 站点 URL:<input type="text" name="url" /><br> <input type="submit" value="提交" /> </form> </body> </html>