1 package com.xiaostudy.servlet;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5
6 import javax.servlet.ServletException;
7 import javax.servlet.annotation.WebServlet;
8 import javax.servlet.http.Cookie;
9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12
13 @WebServlet("/Cookie_2")
14 public class Cookie_2 extends HttpServlet {
15 private static final long serialVersionUID = 1L;
16
17 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18 response.setContentType("text/html;charset=UTF-8");
19 PrintWriter out = response.getWriter();
20 String book = (String)request.getParameter("book");
21 String str = book;
22 Cookie[] cookies = request.getCookies();//得到cookie的集合数组
23 for(int i=0; cookies!=null && i<cookies.length; i++) {//循环cookie
24 if("book".equals(cookies[i].getName())) {//看看以前有没有放过
25 String[] books = cookies[i].getValue().split("-");//做切割
26 for(int j=0; j<books.length; j++) {//循环元素
27 if(!book.equals(books[j])) {//排除已经点击过的
28 str = str + "-" + books[j];
29 }
30 }
31 }
32 }
33 Cookie ck = new Cookie("book", str);//创建一个cookie,并且添加name和value
34 ck.setPath("/");//说明为当前的应用
35 ck.setMaxAge(5);//保存cookie的时间,单位为秒
36 response.addCookie(ck);//服务器向浏览器添加cookie
37 out.print("成功添加书籍:" + book + "<br/>2秒后返回主页。。。");//输出到浏览器的信息
38
39 //响应消息头,2秒后跳转到指定页面
40 response.setHeader("refresh", "2;url=" + request.getContextPath() + "/Cookie_1");
41 }
42
43 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
44 doGet(request, response);
45 }
46
47 }