public class CookiesServlet1 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/>");
Map<String, Book> map = Db.getAll();
for (Map.Entry<String, Book> entry : map.entrySet()) {
Book book = entry.getValue();
out.write("<a href='/NANA/servlet/CookiesServlet2?id="
+ book.getId() + "' target='_blank'>" + book.getName()
+ "</a><br/>"); } // 显示曾经看过的商品
out.write("<br/>你曾经看过:<br/>");
Cookie cookies[] = request.getCookies();
for (int i = 0; cookies != null && i < cookies.length; i++) {
if (cookies[i].getName().equals("bookHistory")) {
String ids[] = cookies[i].getValue().split("\\,");
for (String id : ids) {
Book book = (Book) Db.getAll().get(id);
out.print(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<String, Book>(); static {
map.put("1", new Book("1", "javaweb", "老张", "一本好书"));
map.put("2", new Book("2", "jdbc", "aaa", "2ben好书"));
map.put("3", new Book("3", "spring", "bbb", "3本好书"));
map.put("4", new Book("4", "struts", "cccc", "4本好书"));
map.put("5", new Book("5", "hibernet", "ddd", "5本好书"));
} public static Map<String, Book> getAll() {
return map;
}
} class Book {
private String id;
private String name;
private String author;
private String description; public Book() {
super();
// TODO Auto-generated constructor stub
} public Book(String id, String name, String author, String description) {
super();
this.id = id;
this.name = name;
this.author = author;
this.description = description;
} 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 getDescription() {
return description;
} public void setDescription(String description) {
this.description = description;
} }