Java-web——Cookie技术
下面通过一个实例来说一下Cookie一些函数的用处:
cookie可以用来在用户计算机上保存一些用户数据,当我们没有使用Cookie的setMaxAge方法对其设置cookie有效期,那么如果用户关闭这个网站的应用进程Cookie就会消失,不会保存在本地。如果设置了有效期(比如下面代码我设置的有效期为1个月),那么Cookie就会保存在系统硬盘上(由浏览器存放)
package test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CookieDemo
*/
@WebServlet("/CookieDemo")
public class CookieDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("上次访问时间为:");
//获取用户Cookie,如果没有就不输出上次用户访问时间,否则就输出
Cookie cookies[] = request.getCookies(); //getCookies方法获取用户Cookie数组
//遍历cookie数组,并取出cookie对象的名字和值
for(int i=0;cookies!=null && i<cookies.length;++i) {
//通过getName方法获取cookie的名字
if(cookies[i].getName().equals("lastAccessTime")) {
//通过getValue方法获取cookie的值,并把这个数字字符串转换为长整型
long cookieValue = Long.parseLong(cookies[i].getValue());
//我们下面给lastAccessTime设置的值是当前时间毫秒数,这样我们直接把这个毫秒数给Date类当参数转换为当前日期时间
Date date = new Date(cookieValue);
out.print(date.toLocaleString());
}
}
//更新lastAccessTime的值为当前时间毫秒数,Cookie两个参数都是字符串,键——值
Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
cookie.setMaxAge(1*30*24*3600); //设置过期时间,以秒为单位(我这里设置的是1个月
cookie.setPath("/day02"); //设置浏览器以那个为前缀时带上设置的Cookie,如果你访问/day01/...就不会带上这个Cookie
response.addCookie(cookie);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
第一次访问http://localhost:8080/day02/CookieDemo不会输出上次的时间,但是之后就会输出了(这就是利用了cookie保存了上次登录的时间
有时我们会删除网站的Cookie,一种方法就是找到浏览器放置Cookie的位置,删掉它。另外一种就是通过脚本删除(或者网站上提供这个方法,我们下面程序就这样做)CookieDemo.java
package test; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class CookieDemo */ @WebServlet("/CookieDemo") public class CookieDemo extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //------------------------------------------- out.print("<a href='/day02/CookieDemo1'>清除Cookie</a><br>"); //------------------------------------------- out.print("上次访问时间为:"); //获取用户Cookie,如果没有就不输出上次用户访问时间,否则就输出 Cookie cookies[] = request.getCookies(); //getCookies方法获取用户Cookie数组 //遍历cookie数组,并取出cookie对象的名字和值 for(int i=0;cookies!=null && i<cookies.length;++i) { //通过getName方法获取cookie的名字 if(cookies[i].getName().equals("lastAccessTime")) { //通过getValue方法获取cookie的值,并把这个数字字符串转换为长整型 long cookieValue = Long.parseLong(cookies[i].getValue()); //我们下面给lastAccessTime设置的值是当前时间毫秒数,这样我们直接把这个毫秒数给Date类当参数转换为当前日期时间 Date date = new Date(cookieValue); out.print(date.toLocaleString()); } } //更新lastAccessTime的值为当前时间毫秒数,Cookie两个参数都是字符串,键——值 Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+""); cookie.setMaxAge(1*30*24*3600); //设置过期时间,以秒为单位(我这里设置的是1个月 cookie.setPath("/day02"); //设置浏览器以那个为前缀时带上设置的Cookie response.addCookie(cookie); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
CookieDemo1.java
package test; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class CookieDemo1 */ @WebServlet("/CookieDemo1") public class CookieDemo1 extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+""); cookie.setMaxAge(0); cookie.setPath("/day02"); response.addCookie(cookie); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
效果如下:
下面给出一个·服务器用Cookie记录客户浏览器浏览商品的信息。我们一共让Cookie保存客户之前浏览过的最多三个物品的id,然后利用物品id输出物品名字。而且输出浏览物品的信息按照时间近的优先输出。
CookieDemo.java
package test; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class CookieDemo */ @WebServlet("/CookieDemo") public class CookieDemo extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // 1、输出网站所有商品 out.print("网站商品如下:"); Map<String, Book> map = Db.getAll(); for(Map.Entry<String,Book> entry:map.entrySet()) { Book book = entry.getValue(); out.print("<a href='/day02/CookieDemo1?id="+book.getId()+"' target='_blank'>"+book.getName()+"</a><br/>"); } //2、显示用户看过的商品(最多三个 out.print("之前看过商品:"); Cookie cookies[] = request.getCookies(); for(int i=0;cookies!=null && i<cookies.length;++i) { if(cookies[i].getName().equals("historyids")) { String historyids = cookies[i].getValue(); //out.print(historyids+"展示"+"<br/>"); String[] ids = historyids.split("\\#"); //写成//#这样就算‘#’是特殊字符也没事 for(String id:ids) { //out Book book = map.get(id); out.print(book.getName()+"<br/>"); } //break; } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } class Db { //存放书籍信息的数据库类 private static Map<String, Book> map = new LinkedHashMap(); static { map.put("1", new Book("1", "java_web", "张三", "好书")); map.put("2", new Book("2", "web", "李四", "好书")); map.put("3", new Book("3", "操作系统", "王五", "好书")); map.put("4", new Book("4", "Unix", "Lala", "好书")); map.put("5", new Book("5", "Linux", "Lisa", "好书")); } public static Map getAll() { return map; } } class Book { //书籍类 private String id, name, author, description; public Book() { super(); // TODO Auto-generated constructor stub } public Book(String id, String name, String author, String description) { super(); this.id = id; this.name = name; this.author = author; this.description = description; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
CookieDemo1.java
package test; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.LinkedList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class CookieDemo1 */ @WebServlet("/CookieDemo1") public class CookieDemo1 extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //根据用户传来的id,显示书籍信息 String id = request.getParameter("id"); Book book = (Book) Db.getAll().get(id); out.print(book.getName()+"<br/>"); out.print(book.getAuthor()+"<br/>"); out.print(book.getDescription()+"<br/>"); //更新Cookie String cookieValue = buildCookieValue(id,request); //out.print(cookieValue+"<br/>"); Cookie cookie = new Cookie("historyids",cookieValue); cookie.setMaxAge(1*7*24*60*60); //设置过期时间为1星期 cookie.setPath("/day02"); response.addCookie(cookie); } private String buildCookieValue(String id, HttpServletRequest request) { // TODO Auto-generated method stub String historyids = null; Cookie cookies[] = request.getCookies(); for(int i=0;cookies!=null && i<cookies.length;++i) { if(cookies[i].getName().equals("historyids")) { historyids = cookies[i].getValue(); //break; } } if(historyids==null) { return id; } LinkedList<String> list = new LinkedList(Arrays.asList(historyids.split("\\#"))); if(list.contains(id)) { list.remove(id); }else if(list.size()>=3) { list.removeLast(); } list.addFirst(id); StringBuffer sb = new StringBuffer(); for(String s : list) { sb.append(s+"#"); } return sb.deleteCharAt(sb.length()-1).toString(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
保存Cookie信息的字符中不能使用逗号,即",",否则会出错: