Servlet会话管理二(Cookie)
Cookie是在HTTP协议下,将服务器传递给浏览器的的少量信息保存到浏览器客户端的一种技术,通过这种技术,即使在浏览器被关闭或链接中断的情况下,用户仍可以维护Cookie中的数据。
Cookie是经由服务器端的程序通过HTTP请求和响应发送到浏览器客户端的,是HTTP header的组成部分,因此其传输由HTTP协议控制。
Cookie的问题在于用户可以通过改变其浏览器设置来拒绝接受cookie
1个Cookie包含1个name,1个value,以及可选的属性。
Servlet通过HttpServletResponse.addCookie(Cookie cookie)向浏览器发送cookie,每次添加一个cookie
Servlet通过HttpServletRequest.getCookies()获取浏览器上的cookies
浏览器支持每个网站高达20个cookies,最多支持300个cookies
使用Cookie涉及的类和接口,都在javax.servlet.http包中
public class Cookie extends java.lang.Object implements java.lang.Cloneable, java.io.Serializable public interface HttpServletRequest extends ServletRequest public interface HttpServletResponse extends ServletResponse
Cookie的使用原理
1)服务器端创建Cookie对象,把会话数据存储在Cookie对象中 Cookie cookie = new Cookie(name, value); 2)服务器端将cookie对象发送到浏览器客户端(隐藏发送一个set-cookie名称的响应头) httpServletResponse.addCookie(cookie); 3)浏览器得到服务器发送的cookie,将其保存在浏览器客户端 4)浏览器在下次请求服务器时,会带着cookie信息(包含在HTTP header中) 5)服务器获取浏览器提交的cookie httpServeltRequest.getCookies() // 返回一个Cookie数组,遍历该数组,得到特定名称的cookie;若没有cookie,返回null
通过Servlet创建并设置cookie的三个步骤
Cookie cookie = new Cookie("name", "value"); // 创建一个Cookie cookie.setMaxAge(0); // 设置最大生命周期; 0 表示删除同名的cookie数据 response.addCookie(cookie) // 将cookie发送到浏览器
实例
package app02a.cookie; import java.io.IOException; import java.io.PrintWriter; 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; @WebServlet(name = "PreferenceServlet", urlPatterns = { "/preference" }) public class PreferenceServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final String MENU = "<div style='background:#e8e8e8; padding:15px'>" + "<a href='cookieClass'>Cookie Class</a> " // 这里定义了3个超链接,每个超链接对应一个url,每个url有一个Servlet负责处理 + "<a href='cookieInfo'>Cookie Info</a> " // 表示空格 + "<a href='preference'>Preference</a></div>"; public PreferenceServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html>"); writer.println("<head>"); writer.println("<title>Preference</title>"); writer.println("<style>table {font-size:small;background:NavajoWhite }</style>"); // 文档内嵌样式表 设置html中所有<table>元素的样式 writer.println("</head>"); writer.println("<body>"); writer.println(MENU); writer.println("Please select the values below:"); writer.println("<form method='post'>"); // 请求方法是post,提交的地址默认是当前页面;该表单提交之后由doPost()方法处理 writer.println("<table>"); writer.println("<tr>"); writer.println("<td>Title Font Size:</td>"); writer.println("<td><select name='titleFontSize'>"); writer.println("<option>large</option>"); writer.println("<option>x-large</option>"); writer.println("<option>xx-large</option>"); writer.println("</select></td>"); writer.println("</tr>"); writer.println("<tr>"); writer.println("<td>Title Style & Weight</td>"); writer.println("<td><select name='titleStyleAndWeight' multiple>"); // 属性multiple表名可选择多个选项 writer.println("<option>italic</option>"); writer.println("<option>bold</option>"); writer.println("</select></td>"); writer.println("</tr>"); writer.println("<tr>"); writer.println("<td>Max. Records in Table: </td>"); writer.println("<td><select name='maxRecords'>"); writer.println("<option>5</option>"); writer.println("<option>10</option>"); writer.println("</select></td>"); writer.println("</tr>"); writer.println("<tr>"); writer.println("<td rowspan='2'><input type='submit' value='Set' /></td>"); writer.println("</tr>"); writer.println("</table>"); writer.println("</form>"); writer.println("</body>"); writer.println("</html>"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 处理post的请求 String maxRecords = request.getParameter("maxRecords"); // 获取表单数据 String [] titleStyleAndWeight = request.getParameterValues("titleStyleAndWeight"); // 获取表单数据 String titleFontSize = request.getParameter("titleFontSize"); // 获取表单数据 response.addCookie(new Cookie("maxRecords", maxRecords)); // 添加cookie response.addCookie(new Cookie("titleFontSize", titleFontSize)); // 添加cookie Cookie cookie= new Cookie("titleFontWeight", ""); // 新建cookie cookie.setMaxAge(0); response.addCookie(cookie); cookie = new Cookie("titlFontSize", ""); // 新建cookie cookie.setMaxAge(0); response.addCookie(cookie); // 覆盖之前的重名cookie,只能通过这种方式来删除cookie if (titleStyleAndWeight != null) { for (String style : titleStyleAndWeight) { if (style.equals("bold")) { response.addCookie(new Cookie("titleFontWeight", "bold")); // 添加cookie } else if (style.equals("italic")) { response.addCookie(new Cookie("titleFontStyle", "italic")); // 添加cookie } } } response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html>"); writer.println("<head>"); writer.println("<title>Preference</title>"); writer.println("</head>"); writer.println("<body>"); writer.println(MENU); writer.println("Your preference has beed set.<br /><br />"); writer.println("Max. Records in Table: " + maxRecords + "<br />"); writer.println("Title Font Size: " + titleFontSize + "<br />"); writer.println("Title Font Style & Weight: "); if (titleStyleAndWeight != null) { writer.println("<ul>"); for (String style : titleStyleAndWeight) { writer.println("<li>" + style + "</li>"); } writer.println("</ul>"); } writer.println("</body>"); writer.println("</html>"); } }
package app02a.cookie; import java.io.IOException; import java.io.PrintWriter; 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; @WebServlet(name = "CookieClassServlet", urlPatterns = { "/cookieClass" }) public class CookieClassServlet extends HttpServlet { private static final long serialVersionUID = 1L; private String[] methods = {"clone", "getcomment", "getDomain", "getmaxAge", "getName", "getPath", "getSecure", "getValue", "getVersion", "isHttpOnly", "setComment", "setDomain", "setHttpOnly", "setMaxAge", "setPath", "setSecure", "setValue", "setVersion"}; public CookieClassServlet() { super(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie [] cookies = request.getCookies(); // 从浏览器获取cookies Cookie maxRecordsCookie = null; if (cookies != null) { for (Cookie cookie : cookies) { // 遍历 cookies数组,找到特定名称的cookie if (cookie.getName().equals("maxRecords")) { maxRecordsCookie = cookie; break; } } } int maxRecords = 5; // default if (maxRecordsCookie != null) { try { maxRecords = Integer.parseInt(maxRecordsCookie.getValue()); // 获取指定cookie的值 } catch (NumberFormatException e) { e.printStackTrace(); } } response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html>"); writer.println("<head>"); writer.println("<title>Cookie Class</title>"); writer.println("</head>"); writer.println("<body>"); writer.println(PreferenceServlet.MENU); writer.println("<div>"); writer.println("Here are some of the methods in javax.servlet.http.Cookie"); writer.println("<ul>"); for (int i=0; i < maxRecords; i++) { writer.println("<li>" + methods[i] + "</li>"); } writer.println("</ul>"); writer.println("</body>"); writer.println("</html>"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package app02a.cookie; import java.io.IOException; import java.io.PrintWriter; 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; @WebServlet(name = "CookieInfoServlet", urlPatterns = { "/cookieInfo" }) public class CookieInfoServlet extends HttpServlet { private static final long serialVersionUID = 1L; public CookieInfoServlet() { super(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie [] cookies = request.getCookies(); // 获取随HTTP请求传递过来的cookie, 只能获得所有的cookie的数组,然后遍历数组得到指定的cookie StringBuilder styles = new StringBuilder(); styles.append(".title {"); if (cookies != null) { for (Cookie cookie : cookies) { // 遍历cookie数组 String name = cookie.getName(); String value = cookie.getValue(); if (name.equals("titleFontSize")) { styles.append("font-size:" + value + ";"); } else if (name.equals("titleFontWeight")) { styles.append("font-weight:" + value + ";"); } else if (name.equals("titleFontStyle")) { styles.append("font-style:" + value + ";"); } } } styles.append("}"); response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html>"); writer.println("<head>"); writer.println("<title>Cookie Info</title>"); writer.println("<style>"); writer.println(styles.toString()); writer.println("</style>"); writer.println("</head>"); writer.println("<body>"); writer.println(PreferenceServlet.MENU); writer.println("<div class='title'>"); writer.println("Session Management WithNode Cookies:"); writer.println("</div>"); writer.println("<div>"); if (cookies == null) { writer.println("No cookie in this HTTP response."); } else { writer.println("<br />"); writer.println("Cookies in this HTTP reponse:"); for (Cookie cookie : cookies) { writer.println("<br />"); writer.println(cookie.getName() + ":" + cookie.getValue()); } } writer.println("</div>"); writer.println("</body>"); writer.println("</html>"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }