孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

    cookie是一小块可以嵌入在HTTP请求和应答中的数据。典型情况下,Web服务器将cookie值嵌入到应答的首部,而浏览器则在其以后的请求中都将携带同样的cookie。cookie的信息中可以有一部分用来存储会话ID,这个ID被服务器用来将某些HTTP请求绑定在会话中。cookie由浏览器保存在客户端,通常保存在一个名为cookie.txt的文件。cookie还含有一些其他属性,诸如可选的注释、版本号以及最长生存期。下面为cookies servlet的代码,它显示了当前请求的首部所包含的所有cookie的一些信息。

     

 1 import javax.servlet.*;
 2 import javax.servlet.http.*;
 3 
 4 /**
 5 * <p>This is a simple servlet that displays all of the
 6 * Cookies present in the request
 7 */
 8 public class Cookies extends HttpServlet
 9 {
10 
11     /**
12     * <p>Performs the HTTP GET operation
13     *
14     * @param req The request from the client
15     * @param resp The response from the servlet
16     */
17     public void doGet(HttpServletRequest req,
18     HttpServletResponse resp)
19     throws ServletException, java.io.IOException
20     {
21 
22         // Set the content type of the response
23         resp.setContentType("text/html");
24 
25         // Get the PrintWriter to write the response
26         java.io.PrintWriter out = resp.getWriter();
27 
28         // Get an array containing all of the cookies
29         Cookie cookies[] = req.getCookies();
30 
31         // Write the page header
32         out.println("<html>");
33         out.println("<head>");
34         out.println("<title>Servlet Cookie Information</title>");
35         out.println("</head>");
36         out.println("<body>");
37 
38         if ((cookies == null) || (cookies.length == 0)) {
39         out.println("No cookies found");
40         }
41         else {
42             out.println("<center><h1>Cookies found in the request</h1>");
43 
44             // Display a table with all of the info
45             out.println("<table border>");
46             out.println("<tr><th>Name</th><th>Value</th>" +
47             "<th>Comment</th><th>Max Age</th></tr>");
48 
49             for (int i = 0; i < cookies.length; i++) {
50                 Cookie c = cookies[i];
51                 out.println("<tr><td>" + c.getName() + "</td><td>" +
52                 c.getValue() + "</td><td>" +
53                 c.getComment() + "</td><td>" +
54                 c.getMaxAge() + "</td></tr>");
55             }
56             out.println("</table></center>");
57         }
58         // Wrap up
59         out.println("</body>");
60         out.println("</html>");
61         out.flush();
62     }
63 }


web.xml的配置中加入

<servlet>
        <servlet-name>Cookies</servlet-name>
        <servlet-class>Cookies</servlet-class>
</servlet>

 

<servlet-mapping>
        <servlet-name>Cookies</servlet-name>
        <url-pattern>/servlets/servlet/Cookies</url-pattern>
</servlet-mapping>

 

在浏览器中输入http://localhost:9090/examples/servlets/servlet/Cookies会看到结果

posted on 2012-06-17 17:45  孤独的猫  阅读(331)  评论(0编辑  收藏  举报