【JavaWeb】Cookie

Cookie是客户端技术,程序把每个用户的数据以cookie的形式写给用户各自的浏览器。当用户使用浏览器再去访问服务器中的web资源时,就会带着各自的数据去。这样,web资源处理的就是用户各自的数据了。

//网站首页:显示用户上次访问时间
public class CookieDemo1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write("您上次访问时间是:");  //lastAccessTime=2323878327
		
		//您上次访问时间
		Cookie cookies[] = request.getCookies();
		for(int i=0;cookies!=null&& i<cookies.length;i++){
			Cookie cookie = cookies[i];
			if(cookie.getName().equals("lastAccessTime")){
				long time = Long.parseLong(cookie.getValue());
				Date d = new Date(time);
				response.getWriter().write(d.toLocaleString());
			}
		}
		
		//向浏览器发送本次访问的时间
		Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
		//cookie.setMaxAge(0);
		cookie.setPath("/test");
		response.addCookie(cookie);
		
		
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}


//代表首页
public class CookieDemo2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		//显示网站所有商品
		out.write("本网站有如下商品<br/><br/>");
		Set<Map.Entry<String, Book>> set = Db.getAllBook().entrySet();
		for(Map.Entry<String, Book> me : set){
			String id = me.getKey();
			Book book = me.getValue();
			out.write("<a href='/test/servlet/CookieDemo3?id="+id+"' target='_blank'>"+book.getName()+"</a><br/>");
		}
		
		
		//显示用户曾经浏览过的商品
		out.write("<br/><br/><br/>您看过如下商品:<br/><br/>");
		Cookie cookies[] = request.getCookies();
		for(int i=0;cookies!=null && i<cookies.length;i++){
			if(cookies[i].getName().equals("bookHistory")){   //bookHistory=1_2_3
				String value = cookies[i].getValue();
				String ids[] = value.split("\\_");  //_
				for(String id: ids){
					Book book = (Book) Db.getAllBook().get(id);
					out.write(book.getName()+"<br/>");
				}
			}
		}
		
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}
}

class Db{
	private static Map<String,Book> map = new LinkedHashMap();
	static{
		map.put("1", new Book("1","javaweb开发","author1","一本好书"));
		map.put("2", new Book("2","jdbc开发","author1","一本好书"));
		map.put("3", new Book("3","sprng开发","author2","一本好书"));
		map.put("4", new Book("4","hibernate开发","author1","一本好书"));
		map.put("5", new Book("5","strurs开发","author2","一本好书"));
	}
	
	public static Map getAllBook(){
		return map;
	}
}

class Book{
	
	private String id;
	private String name;
	private String author;
	private String discription;
	
	public Book() {
	}
	public Book(String id, String name, String author, String discription) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
		this.discription = discription;
	}
	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 getDiscription() {
		return discription;
	}
	public void setDiscription(String discription) {
		this.discription = discription;
	}
}

//显示商品详细信息
public class CookieDemo3 extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		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.getAllBook().get(id);
		out.write(book.getId() + "<br/>");
		out.write(book.getName() + "<br/>");
		out.write(book.getAuthor() + "<br/>");
		out.write(book.getDiscription() + "<br/>");
		
		//给用户发cookie
		String value = makeBookHistory(request,id);
		Cookie cookie = new Cookie("bookHistory",value);
		cookie.setMaxAge(3600);
		response.addCookie(cookie);
	}

	//创建向用户发送的 cookie值
	private String makeBookHistory(HttpServletRequest request, String id) {
		
		String bookHistory = null;
		Cookie cookies[] = request.getCookies();
		for(int i=0;cookies!=null && i<cookies.length;i++){
			if(cookies[i].getName().equals("bookHistory")){
				bookHistory = cookies[i].getValue();
			}
		}
		
		//bookHistory=null    3    bookHistory=3
		//bookHistory=1       3    bookHistory=3_1
		//bookHistory=1_4_5   3    bookHistory=3_1_4
		//bookHistory=1_3_5   3    bookHistory=3_1_5
		
		
		if(bookHistory==null){
			bookHistory = id;
			return bookHistory;
		}
		
		//bookHistory=1_3_5 
		LinkedList<String> list = new LinkedList(Arrays.asList(bookHistory.split("\\_")));  //list[1,3,5]   3  
		/*if(list.contains(id)){
			list.remove(id);
			list.addFirst(id);
		}else{
			if(list.size()>=3){     //list[1,4,5]   3  
				list.removeLast();
				list.addFirst(id);
			}else{
				list.addFirst(id);
			}
		}*/
		
		if(list.contains(id)) list.remove(id);
		else{
			if(list.size()>=3) list.removeLast();
		}
		list.addFirst(id);
		
		StringBuffer sb = new StringBuffer();
		for(String bid : list){
			sb.append(bid+"_");
		}
		sb.deleteCharAt(sb.length()-1);
		return sb.toString();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值