zoukankan      html  css  js  c++  java
  • java_Cookies_1_商品浏览历史记录servlet2

    public class CookiesServlet2 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.getAll().get(id);
    		out.write(book.getId() + "<br/>");
    		out.write(book.getName() + "<br/>");
    		out.write(book.getAuthor() + "<br/>");
    		out.write(book.getDescription() + "<br/>");
    
    		// 构建Cooikes回写给浏览器
    		String cookieValue = buildCookie(id, request);
    
    		Cookie cookie = new Cookie("bookHistory", cookieValue);
    		cookie.setMaxAge(1 * 30 * 24 * 60 * 60);
    		cookie.setPath("/NANA");
    		response.addCookie(cookie);
    	}
    
    	private String buildCookie(String id, HttpServletRequest request) {
    		// if none cookie, bookHistory=null, cookie value =1
    
    		// if contain cookie,bookHistory=2,5,1 return 1 2 5
    
    		// cookieHistory=2,5,4 browns 1 return 1,2,5 到了列表最大值
    
    		// cookieHistory=2,5 browns 1 return 1,2,5 没到最大值
    
    		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();
    			}
    		}
    
    		if (bookHistory == null) {
    			return id;
    		}
    
    		LinkedList<String> list = new LinkedList<String>(
    				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);
    			}
    		}
    		
    		StringBuffer sb = new StringBuffer();
    		for(String bid:list){
    			sb.append(bid+",");
    		}
    		
    		
    		return sb.deleteCharAt(sb.length()-1).toString();
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    
    		doGet(request, response);
    	}
    
    }
    


  • 相关阅读:
    H
    并查集
    H
    Supermarket (贪心 并查集)
    H
    M
    N-Find a way
    HDU 4035 Maze
    #386. 【UNR #3】鸽子固定器
    P4688 [Ynoi2016]掉进兔子洞
  • 原文地址:https://www.cnblogs.com/MarchThree/p/3720430.html
Copyright © 2011-2022 走看看