• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Java Servlet编程应用之Cookie使用方法

servlet/jsp 搞代码 7年前 (2018-06-18) 153次浏览 已收录 0个评论

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

欢迎大家阅读《Java Servlet编程应用之Cookie使用方法》,跪求各位点评,若觉得好的话请收藏本文,by 搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Java Servlet编程应用之Cookie使用方法
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址