您的位置:首页 > 其它

Cookie实现会话跟踪

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

package sample;

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 CookiesTest extends HttpServlet

{

/**

* <p>Performs the HTTP GET operation

*

* @param req The request from the client

* @param resp The response from the servlet

*/

public void doGet(HttpServletRequest req,

HttpServletResponse resp)

throws ServletException, java.io.IOException

{

// Set the content type of the response

resp.setContentType("text/html");

// 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("No cookies found");

}

else {

out.println("<center><h1>Cookies found in the request</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();

}

}

l值得注意的是HttpServletRequest对象有一个getCookies的方法,它可以返回当前请求中的cookie对象的一个数组。
l关于是否应当使用cookie有很多的争论,因为一些人认为cookie可能会造成对隐私权的侵犯。有鉴于此,大部分浏览器允许用关闭cookie功能,然而这使我们跟踪会话变得更加困难。如果不能依赖cookie的支持又该怎办呢?你将不得不使用URL
rewriting,这种方法很久以前就被CGI所使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: