六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 40|回复: 0

servlet学习笔记2-servlet中得到cookie的信息

[复制链接]

升级  44%

32

主题

32

主题

32

主题

秀才

Rank: 2

积分
116
 楼主| 发表于 2013-1-27 05:51:17 | 显示全部楼层 |阅读模式
  Servlet API 提供了一个Cookie 类,封装了对Cookie 的一些操作。Servlet 可以创建一个新的Cookie,设置它的关键字、值及有效期等属性,然后把Cookie 设置在HttpServletResponse 对象中发回浏览器,还可以从HttpServletRequest 对象中获取Cookie。

  编程思路:Cookie 在实际的Servlet 编程中是很广泛应用,下面是一个从Servlet 中获取Cookie 信息的例子。

  ShowCookies.java 的源代码如下:

import javax.servlet.*;import javax.servlet.http.*;/*** <p>This is a simple servlet that displays all of the* Cookies present in the request*/public class ShowCookies extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException {  // Set the content type of the response  resp.setContentType("text/html;charset=gb2312");  // Get the PrintWriter to write the response  java.io.PrintWriter out = resp.getWriter();  // Get an array containing all of the cookies  Cookie cookies[] = req.getCookies();  // Write the page header  out.println("<html>");  out.println("<head>");  out.println("<title>Servlet Cookie Information</title>");  out.println("</head>");  out.println("<body>");  if ((cookies == null) || (cookies.length == 0)) {   out.println("没有 cookies ");  }  else {   out.println("<center><h1>响应消息中的Cookies 信息 </h1>");   // Display a table with all of the info   out.println("<table border>");   out.println("<tr><th>Name</th><th>Value</th>" + "<th>Comment</th><th>Max Age</th></tr>");   for (int i = 0; i < cookies.length; i++) {    Cookie c = cookies[i];    out.println("<tr><td>" + c.getName() + "</td><td>" +    c.getValue() + "</td><td>" + c.getComment() + "</td><td>" + c.getMaxAge() + "</td></tr>");  }  out.println("</table></center>"); } // Wrap up out.println("</body>"); out.println("</html>"); out.flush();}/*** <p>Initialize the servlet. This is called once when the* servlet is loaded. It is guaranteed to complete before any* requests are made to the servlet* @param cfg Servlet configuration information*/public void init(ServletConfig cfg)throws ServletException{ super.init(cfg);}/*** <p>Destroy the servlet. This is called once when the servlet* is unloaded.*/public void destroy(){ super.destroy();}}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表