Servlet(3):Cookie

 概念

Cookie是存储在客户端计算机上的文本文件,并保留了各种跟踪信息。Java Servlet支持HTTP Cookie。

识别返回用户包括三个步骤:

(1) 服务器脚本向浏览器发送一组Cookie。例如:姓名、年龄或识别号码等。

(2) 浏览器将这些信息存储在本地计算机上,以备将来使用。

(3) 当下一次浏览器向Web服务器发送任何请求时,浏览器会把这些Cookie信息发送到服务器,服务器将使用这些信息来识别用户。

 

注意事项
(1) 创建一个Cookie对象(注意要Encode / 无论是名字还是值,都不应该包含这字符: [ ] ( ) = , " / ? @ : ;)

Cookie name = new Cookie("name", URLEncoder.encode(request.getParameter("name"), "UTF-8"));

(2) 设置Cookie的有效时间(当设置0时意思为删除Cookie)

cookie.setMaxAge(60*60*24);
cookie.setMaxAge(0);

 

例子

(1) 登录成功后,[Welcome.Servlet]Response了两个Cookie: userId, password给浏览器

(2) 浏览器点[返回],发送Request给[Login.Servlet]并且把Cookie信息又发送到服务器

(3) 最终[Login.Servlet]Response了Cookie的一览信息

 1 package com.servlettest.cookie;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.Cookie;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 
13 /**
14  * Servlet implementation class Login
15  */
16 @WebServlet("/login")
17 public class Login extends HttpServlet {
18 
19     private static final long serialVersionUID = 1L;
20 
21     /**
22      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
23      */
24     @Override
25     protected void doGet(HttpServletRequest request, HttpServletResponse response)
26             throws ServletException, IOException {
27 
28         response.setContentType("text/html");
29 
30         request.setCharacterEncoding("UTF-8");
31         response.setCharacterEncoding("UTF-8");
32 
33         // 获取Session
34         Cookie[] cookies = request.getCookies();
35 
36         PrintWriter out = response.getWriter();
37         out.println("<!DOCTYPE html>");
38         out.println("<html>");
39         out.println("<head>");
40         out.println("<title>Login Page</title>");
41         out.println("</head>");
42         out.println("<body>");
43         if (cookies != null && cookies.length > 0) {
44             out.println("<p>Cookies:</p>");
45             out.println("<table border=\"1\">");
46             out.println(
47                     "<tr><td>Name</td><td>Comment</td><td>Domain</td><td>MaxAge</td><td>Path</td><td>Value</td><td>Version</td></tr>");
48             for (int i = 0; i < cookies.length; i++) {
49                 out.println("<tr>");
50                 out.println("<td>" + cookies[i].getName() + "</td>");
51                 out.println("<td>" + cookies[i].getComment() + "</td>");
52                 out.println("<td>" + cookies[i].getDomain() + "</td>");
53                 out.println("<td>" + cookies[i].getMaxAge() + "</td>");
54                 out.println("<td>" + cookies[i].getPath() + "</td>");
55                 out.println("<td>" + cookies[i].getValue() + "</td>");
56                 out.println("<td>" + cookies[i].getVersion() + "</td>");
57                 out.println("</tr>");
58             }
59             out.println("</table>");
60             out.println("<br/>");
61         }
62         out.println("<form action=\"welcome\" method=\"POST\">");
63         out.println("帐号: <input type=\"text\" name=\"userId\"/><br/>");
64         out.println("密码: <input type=\"password\" name=\"password\"/><br/>");
65         out.println("<input type=\"submit\" value=\"提交\"/>");
66         out.println("</body>");
67         out.println("</html>");
68     }
69 
70     /**
71      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
72      */
73     @Override
74     protected void doPost(HttpServletRequest request, HttpServletResponse response)
75             throws ServletException, IOException {
76         doGet(request, response);
77     }
78 }
package com.servlettest.cookie;

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 Welcome
 */
@WebServlet("/welcome")
public class Welcome extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private static final int VALID_TIME = 60;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String userId = request.getParameter("userId");
        String password = request.getParameter("password");

        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Login Page</title>");
        out.println("</head>");
        out.println("<body>");
        if ("123".equals(password)) {
            out.println("欢迎您, " + userId);
            // 创建Ssession
            addCookie(userId, password, response);
        } else {
            out.println("您的帐号或密码错误!");
        }
        out.println("<a href = \"login\">返回</a>");
        out.println("</body>");
        out.println("</html>");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    private void addCookie(String userId, String password, HttpServletResponse response) throws IOException {
        Cookie userIdCookie = new Cookie("userId", URLEncoder.encode(userId, "UTF-8"));
        Cookie passwordCookie = new Cookie("password", URLEncoder.encode(password, "UTF-8"));
        userIdCookie.setMaxAge(VALID_TIME);
        passwordCookie.setMaxAge(VALID_TIME);
        response.addCookie(userIdCookie);
        response.addCookie(passwordCookie);
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <welcome-file-list>
        <welcome-file>login</welcome-file>
    </welcome-file-list>
</web-app>

 

posted @ 2017-09-08 10:59  Storm_L  阅读(138)  评论(0编辑  收藏  举报