【JavaWeb】Cookie__Java

來源:互聯網
上載者:User

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_3String 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/>");//給使用者發cookieString 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_5if(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);}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.