教你使用cookie法,查看最近看过的书

导读:本篇文章讲解 教你使用cookie法,查看最近看过的书,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

教你使用cookie法,查看最近看过的书

import java.io.Serializable;

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,查询数据库找出书,输出书的详细信息
String id = request.getParameter("id");
Book book = BookDao.getBook(id);
if(book==null){
response.getWriter().write("找不到这本书!");
return;
}else{
response.getWriter().write("<h2>书名:"+book.getName()+"</h2>");
response.getWriter().write("<h4>作者:"+book.getAuth()+"</h4>");
response.getWriter().write("<h4>售价:"+book.getPrice()+"</h4>");
response.getWriter().write("<h4>出版社:"+book.getPublish()+"</h4>");
response.getWriter().write("<h4>描述信息:"+book.getDescription()+"</h4>");
}

//2.发送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{
//说明之前有历史看过的书的记录,需要根据历史记录算一个新的记录出来
String [] olds = findC.getValue().split(",");
StringBuffer buffer = new StringBuffer();
buffer.append(book.getId()+",");
for(int i = 0;i<olds.length && buffer.toString().split(",").length<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(36002430);
lastC.setPath(request.getContextPath());
response.addCookie(lastC);

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/17001.html

(0)
小半的头像小半

相关推荐

半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!