教你使用cookie法,查看最近看過的書
import java.io.Serializable;
創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供柳北網(wǎng)站建設(shè)、柳北做網(wǎng)站、柳北網(wǎng)站設(shè)計、柳北網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、柳北企業(yè)網(wǎng)站模板建站服務(wù),10多年柳北做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
public class Book implements Serializable {
private String id;
private String name;
private String price;
private String auth;
private String publish;
private String description;
public Book() {
}
public Book(String id, String name, String price, String auth,
String publish, String description) {
super();
this.id = id;
this.name = name;
this.price = price;
this.auth = auth;
this.publish = publish;
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
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 = 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;
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//1.獲取要看的書的id,查詢數(shù)據(jù)庫找出書,輸出書的詳細信息
String id = request.getParameter("id");
Book book = BookDao.getBook(id);
if(book==null){
response.getWriter().write("找不到這本書!");
return;
}else{
response.getWriter().write("
//2.發(fā)送cookie保存最后看過的書
// --- 1 --> 1
// 1 --2,1 --> 2,1
// 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
String ids = "";
Cookie [] cs = request.getCookies();
Cookie findC = null;
if(cs!=null){
for(Cookie c : cs){
if("last".equals(c.getName())){
findC = c;
}
}
}
if(findC == null){
//說明之前沒有看過書的記錄
ids += book.getId();
}else{
//說明之前有歷史看過的書的記錄,需要根據(jù)歷史記錄算一個新的記錄出來
String [] olds = findC.getValue().split(",");
StringBuffer buffer = new StringBuffer();
buffer.append(book.getId()+",");
for(int i = 0;i
if(!old.equals(book.getId())){
buffer.append(old+",");
}
}
ids = buffer.substring(0, buffer.length()-1);
}
Cookie lastC = new Cookie("last",ids);
lastC.setMaxAge(36002430);
lastC.setPath(request.getContextPath());
response.addCookie(lastC);
}