cookie是java Servlet实现Session创建存取以及url重写代码示例
iis7站长之家通过浏览器保存在www用户端硬盘上的一个文本文件,这个文件中包含了文本信息文本信息的内容是以“名/值”对的形式进行储存。可以让web开发者通过程序读写这个文本文件在Windows XP中保存Cookie的目录是:C:Documents and Settings用户名Cookies。Cookie的作用是解决浏览器用户与web服务器之间无状态通信。
注意:
cookie的大小和数量是有限制的。
cookie在个人硬盘上所保存的文本信息是以明文格式进行保存的,没有任何的加密措施。
浏览器可以设定不使用cookie。
实例代码1
文件 cookiesInput.html
<html>
<head>
<title>cookie input page</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
请输入用户名<br>
<form name="form1" action="/article/SetCookiesServlet/index.html" method="post" >
<table border="0">
<tr><td>用户名:</td>
<td><input type="text" name="username">
</td></tr>
<tr><td colspan="2" align="center">
<input name="submit" value="submit" type="submit">
</td></tr>
</table>
</form>
</body>
</html>
SetCookiesServlet
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import webbook.util.StringUtil;
public class SetCookiesServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String output = null;
String username = request.getParameter("username");
if (!StringUtil.validateNull(username)) {
Cookie cookie1 = new Cookie("username", StringUtil.filterHtml(username));
// cookie的有效期为1个月
cookie1.setMaxAge(24 * 60 * 60 * 30);
response.addCookie(cookie1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Cookie cookie2 = new Cookie("lastTime", sdf.format(new Date()));
cookie2.setMaxAge(24 * 60 * 60 * 30);
response.addCookie(cookie2);
output = "本次登录时间与用户名已经写到Cookie中";
}
else {
output = "用户名为空,请重新输入";
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>set cookies </title></head>");
out.println("<body>");
out.println("<h2>" + output + "</h2>");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}
}
GetCookiesServlet
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetCookiesServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// 获取所有的cookie值
Cookie[] cookies = request.getCookies();
Cookie cookie = null;
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
if (cookie.getName().equals("username")) {
out.println("用户名:" + cookie.getValue());
}
if (cookie.getName().equals("lastTime")) {
out.println("上次登录时间:" + cookie.getValue());
}
}
out.flush();
out.close();
}
}
销毁Cookie
Cookie cookies[] = request.getCookies();
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
cookies[i].setMaxAge(0);
response.addCookie(cookies[i]);
}
}
实例代码2:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String option = request.getParameter("option");
if ("show".equals(option)) {
//获得请求信息中的Cookie数据
Cookie[] cookies = request.getCookies();
if (cookies != null) {
//找出名称(键)为“cool”的Cookie
for (int i = 0; i < cookies.length; i++) {
if ("cool".equals(cookies[i].getName())) {
out.println("<h2>" + cookies[i].getName() + ":"
+ cookies[i].getValue() + "</h2>");
}
}
}
} else if ("add".equals(option)) {
//创建Cookie对象
Cookie cookie = new Cookie("cool", "yeah!");
//设置生命周期以秒为单位
cookie.setMaxAge(20);
//添加Cookie
response.addCookie(cookie);
}
该servlet对应的url-pattern为/testcookie
当浏览器请求地址“.../tst/testCookie?option=add”时,该Servlet创建一个Cookie对象,存储的键-值对为“cool”-“yeah”。通过response的addCookie方法将该Cookie信息添加到相应信息中。需要注意的是cookie的setMaxAge方法用于设置该cookie生命周期,单位是秒,如果过了这个期间,Cookie将失效。setMaxAge方法的参数如果为负值则表示该Cookie将在浏览器关闭时过期,如果参数为0则表示立刻删除该Cookie。访问该地址,对应的请求和响应的HTTP信息为:
请求:
GET /tst/testCookie?option=add HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, **
Accept-Language: zh-cn
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)
Host: 192.168.5.100:8080
Connection: Keep-Alive
Cookie: cool=yeah!
响应:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 21
Date: Sun, 29 Jun 2008 06:15:26 GMT
<h2>cool:yeah!</h2>
注意,请求协议头中用于携带cookie信息的格式。
Cookie可以用于保持用户的会话状态,但Cookie信息保存在客户端,存在较大的安全隐患,且一般浏览器对Cookie的数目及数据大小有严格的限制。在Web应用中,一般情况下通过HttpSession对象保持会话状态。