服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java servlet 编程及应用之cookie的使用方法

  cookie 是一小块可以嵌入http 请求和响应中的数据,它在服务器上产生,并作为响应头域的一部分返回用户。浏览器收到包含cookie 的响应后,会把cookie 的内容用“关键字/值” 对的形式写入到一个客户端专为存放cookie 的文本文件中。浏览器会把cookie 及随后产生的请求发给相同的服务器,服务器可以再次读取cookie 中存cookie 可以进行有效期设置,过期的cookie 不会发送给服务器。


  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();
}
}
 

  注意:cookie 进行服务器端与客户端的双向交流,所以它涉及到安全性问题。

扫描关注微信公众号