javaWeb_04-Cookie案例-显示商品浏览历史纪录

04-Cookie案例-显示商品浏览历史纪录
显示用户上次浏览过的商品

/

|

显示用户上次浏览过的商品

首页:进入本页可选择要看的商品,刷新之后会有记录


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
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 CookieDemo4_1
 */
@WebServlet("/CookieDemo4_1")
public class CookieDemo4_1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
	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.write("本网站有如下商品:");
		Map map = Db.getAll();
		for(Map.Entry entry:map.entrySet()){
			Book book = entry.getValue();
			out.print(""+book.getName()+"");
			
		}
		//2,显示用户曾经看过的商品
		out.write("您看过的商品如下:");
		Cookie cookies[] = request.getCookies();
		for(int i = 0;cookies != null && i < cookies.length;i++){
			if(cookies[i].getName().equals("bookHistory")){
				String ids[] = cookies[i].getValue().split("\\,");//2,3,1
				System.out.println(Arrays.asList(ids));
				for(String id:ids){
					Book book = Db.getAll().get(id);
					out.print(book.getName());
				}
			}
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

/*-------------------模拟数据库,存储书籍信息---------------------*/
class Db{
	private static LinkedHashMap map = new LinkedHashMap();
	static {
		map.put("1",new Book("1", "数学", "张三", "math"));
		map.put("2",new Book("2", "语文", "里斯", "chinese"));
		map.put("3",new Book("3", "英语", "王五", "english"));
		map.put("4",new Book("4", "化学", "赵六", "chemistry"));
	}
	public static Map getAll(){
		return map;
	}


}
/*-------------------维护对象---------------------*/
class Book{
	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;
	}
	private String id;
	private String name;
	private String author;
	private String 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;
	}
}
	
		

显示商品详细信息,并处理cookie
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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 CookieDemo4_1
 */
@WebServlet("/CookieDemo4_2")
public class CookieDemo4_2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	protected 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");
		System.out.println(id);
		Book  book = Db.getAll().get(id);
		out.write(book.getId());
		out.write(book.getName());
		out.write(book.getAuthor());
		out.write(book.getDescription());
		//2,构建cookie,回写给浏览器
		String cookieValue = BuildCookie(id,request );
		Cookie cookie =new Cookie("bookHistory",cookieValue);
		cookie.setMaxAge(3600*1000);
		cookie.setPath("/day07");
		response.addCookie(cookie);
		
	}

	private String BuildCookie(String id, HttpServletRequest request) {
		/**
		 * 传进来的cookies可能的情况:
		 * 1,2,3 == 2===>2,1,3
		 * 1,2    == 3==>  3,1,2
		 * null    == 2==> 2
		 * 1,2,3 ==4==>  4 1 2  
		 * 
		 * 
		*/
		Cookie cookies[] = request.getCookies();
		StringBuilder sb = new StringBuilder();
		String bookHistory = null;
		for(int i = 0 ;cookies != null && i < cookies.length;i++){
			if(cookies[i].getName().equals("bookHistory")){
				bookHistory = cookies[i].getValue();
				break;
			}
		}
			if(bookHistory == null){
				return id;
			}
			/*怪不得找不到 addFirst方法,原来,不是用的链    linkedList*/
			//ArrayList list = (ArrayList) Arrays.asList(bookHistory.split("\\,"));
			LinkedList list = new LinkedList(Arrays.asList(bookHistory.split("\\,")));
			
		/*		if(list.contains(id)){
					list.remove(id);
					list.addFirst(id)
				}else{
					if(list.size()>=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);
			for(String bid:list){
				sb.append(bid+",");
			}
			
		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
	}

}

		
		

你可能感兴趣的:(servlet,javaWeb)