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);
    	}
    
    }
    


  • 相关阅读:
    jQueryEasyUi行编辑打造增删改查
    css样式DEMO
    jqueryEasyui常用代码
    Jquery easyui tree 一些常见操作
    EasyUI项目中的自定义JS
    easyui里弹窗的两种表现形式
    EasyUI扩展方法
    JS-easyui 扩展easyui.datagrid,添加数据loading遮罩效果代码
    Being a Hero (hdu 3251 最小割 好题)
    AWS携手上海嘉定政府推出首个联合孵化器 为创业公司拓展AWS云服务可用资源
  • 原文地址:https://www.cnblogs.com/MarchThree/p/3720430.html
Copyright © 2011-2022 走看看