Эта статья делится с вами соответствующими методами использования файлов cookie для отображения недавно просмотренных книг для вашей ссылки. Конкретный контент заключается в следующем
1. Бен пакет
импортировать java.io.serializable; Общедоступный класс книга реализует сериализуемые {приватный идентификатор строки; Приватное название строки; частная строковая цена; Private String Auth; Private String Publish; частная строка описание; public book () {} public book (идентификатор строки, имя строки, цена строки, строка Auth, String publish, String description) {super (); this.id = id; this.name = name; this.price = цена; this.auth = auth; this.publish = publish; this.description = описание; } public String getDescription () {return description; } public void setDescription (строка описание) {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 getPrice () {return Price; } public void setPrice (String Price) {this.price = цена; } public String getAuth () {return auth; } public void setAuth (String auth) {this.auth = auth; } public String getPublish () {return publish; } public void setPublish (String publish) {this.publish = publish; }} 2. DAO Package
Импорт java.util.linkedhashmap; импорт java.util.map; Импорт cn.huiyu.ben.book; открытый класс BookDao {Private Static Map <String, Book> BookMap = new LinkedHashmap <String, book> (); private bookdao () {} static {bookmap.put ("1", новая книга ("1", "1111", "11.0", "zqwang", "111 Press", "11111111")); bookmap.put ("2", новая книга ("2", "2222", "22.0", "zqwang", "2222222222")); bookmap.put ("3", новая книга ("3", "3333", "33.0", "zqwang", "3333333333")); } public Static Map <string, book> getBooks () {return quopmap; } public Static Bookbook (String Id) {return bookmap.get (id); }} 3. Сервилет
public void Doget (httpservletRequest, httpservletresponse response) Throws ServletException, ioException {response.setContentType ("text/html; charset = utf-8"); // 1. Запросить все книги в базе данных для отображения карты <строка, book> map = bookdao.getbooks (); for (map.Entry <String, book> intry: map.EntrySet ()) {book book = intry.getValue (); response.getWriter (). write ("<a href = '"+request.getContextPath ()+"/servlet/bookInfoServlet? id ="+book.getId ()+"'>"+book.getName ()+"</a> <br>"); } response.getWriter (). write ("<hr>"); // 2. Покажите книги, которые я прочитал перед cookie [] cs = request.getcookies (); Cookie findc = null; if (cs! = null) {for (cookie c: cs) {if ("last" .equals (c.getname ())) {findc = c; }}} if (findc == null) {response.getWriter (). написать ("Я не читал никаких книг!"); } else {response.getWriter (). написать ("книги, которые вы просмотрели: <br>"); String [] ids = findC.GetValue (). Split (","); для (String ID: IDS) {Book Book = bookDao.getBook (id); response.getWriter (). написать (book.getName ()+"<br>"); }}} 4. Сервилет
public void Doget (httpservletRequest, httpservletresponse response) Throws ServletException, ioException {response.setContentType ("text/html; charset = utf-8"); // 1. Получить идентификатор книги, который будет прочитать, запросите базу данных, чтобы найти книгу, и вывести подробную информацию книги String Id = request.getParameter ("id"); Book Book = bookdao.getbook (id); if (book == null) {response.getWriter (). написать («Эта книга не может быть найдена!»); возвращаться; } else {response.getWriter (). write ("<h1> название:"+book.getName ()+"</h1>"); response.getWriter (). написать ("<h3> автор:"+book.getauth ()+"</h3>"); response.getWriter (). write ("<h3> цена продажи:"+book.getprice ()+"</h3>"); response.getWriter (). write ("<h3> Publisher:"+book.getPublish ()+"</h3>"); response.getWriter (). write ("<h3> Описание:"+book.getDescription ()+"</h3>"); } // 2. Отправьте файлы cookie, чтобы сохранить последнюю книгу, которую вы прочитали // --- 1-> 1 // 1 --2,1-> 2,1 // 2,1--3,2,1-> 3,2,1 // 3,2,1-> 3,2,1-> 4,3,2-> 4,3,2 // 4,3,2 --3,4,2-> 3,4,2. Cookie [] cs = request.getcookies (); Cookie findc = null; if (cs! = null) {for (cookie c: cs) {if ("last" .equals (c.getname ())) {findc = c; }}} if (findc == null) {// Объяснения, которые не читали книгу перед идентификатором += book.getid (); } else {// Объяснения записей книг, которые были прочитаны в истории ранее, и новая запись должна быть рассчитана на основе истории истории [] olds = findc.getValue (). Split (","); StringBuffer Buffer = new StringBuffer (); buffer.append (book.getid ()+","); for (int i = 0; i <Olds.length && buffer.toString (). Split (","). Длина <3; i ++) {string old = olds [i]; if (! old.equals (book.getid ())) {buffer.append (old+","); }} ids = buffer.substring (0, buffer.length ()-1); } Cookie lastc = new cookie ("last", ids); LastC.SetMaxage (3600*24*30); fastc.setpath (request.getContextPath ()); response.addcookie (lastc); }Выше всего об этой статье. Я надеюсь, что для всех будет полезно научиться использовать файлы cookie для отображения недавно просмотренных книг.