深入体验JavaWeb开发内幕——使用Cookie模拟某网站向客户发出提示信息的应用
我们在访问某网站时,例如:购物网站、影视网站等这些网站在你登录时可能会向发出你最近购买的商品或观看过的影片等信息,那么这种效果是如何实现的呢?
具体效果如图:
当用户第一次登录该网站时:
浏览过某资源之后:
当你再次访问该网站时:
你还可以继续浏览那么下次再登录时还会做相似的提示:
相关代码实现:
一个用来封装Book对象的实体类
Book.java
package net.csdn.controller;import java.io.IOException;import java.io.PrintWriter;import java.util.Arrays;import java.util.LinkedList;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.csdn.bookdaoimpl.BookDaoImpl;import net.csdn.bookdomain.Book;public class ProductDescription extends HttpServlet { BookDaoImpl bdi = new BookDaoImpl();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.println("书籍详细信息:"+"<br/>");String id = request.getParameter("id");Book book = bdi.getBookDescription(id);out.println("Id:"+book.getId()+"<br/>");out.println("Name:"+book.getName()+"<br/>");out.println("Author:"+book.getAuthor()+"<br/>");out.println("Description:"+book.getDescription()+"<br/>");//将书号写入到cookieString cookieValue = getBrowseringHistroy(id,request);Cookie cookie = new Cookie("BrowseringHistory",cookieValue);cookie.setMaxAge(2*24*3600);cookie.setPath("/BookDescription");response.addCookie(cookie);}// 获取cookie的返回值private String getBrowseringHistroy(String id, HttpServletRequest request) { String BrowseringHistroy = null; Cookie cookie [] = request.getCookies();for(int i=0;cookie!=null && i<cookie.length;i++){if(cookie[i].getName().equals("BrowseringHistory")){BrowseringHistroy = cookie[i].getValue();}}if(BrowseringHistroy == null){return id;}LinkedList<String> list = new LinkedList(Arrays.asList(BrowseringHistroy.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 cid : list){sb.append(cid+",");}return sb.deleteCharAt(sb.length()-1).toString();//return sb.substring(0,sb.length()-1 ).toString();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}好了赶快自己动手创建一个数据库“book”再建一个相应的存放书籍的表“book”,去自己试一试这种效果吧!