您的位置:首页 > 其它

利用cookie实现查看最近浏览

2017-02-19 21:49 375 查看
[align=left]我们在浏览网页的时候经常会在下一次打开浏览器的时候看到网页提供的最近浏览网页,这些都是怎么做的?[/align]
其实主要用是cookie技术

package entity;
//书的实体类
public class Book {
private String id;
private String name;
private double price ;
public double getPrice() {
return price ;
}
public void setPrice(double price) {
this.price = price ;
}
private String author;
public Book(String id,String name, double price,String author ) {
// TODO Auto-generated constructor stub
this.id =id ;
this.name =name ;
this.price =price ;
this.author =author ;
}
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 ;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price
+ ", author=" + author + "]" ;
}

}

package utils;
import java.util.HashMap;
import java.util.Map;
//模拟数据库操作

import entity.Book;

public class DBUtils {
private static Map<String, Book> books= new HashMap<String,Book>();
//模拟数据库数据
static{
books.put("1" , new Book("1", "java入门",10,"小明" ));
books.put("2" , new Book("2", "oracle入门",10,"小红" ));
books.put("3" , new Book("3", "android入门",50,"小李" ));
books.put("4" , new Book("4", "大数据",90,"小刚" ));
}
//得到所有的书
public static Map<String, Book> getBooks(){
return books ;
}
//根据id查找书籍
public static Book  findBookById(String id ) {

return books .get(id );
}
}
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.prism.impl.Disposer.Target;

import entity.Book;
import utils.DBUtils;

public class BookServlet extends HttpServlet {

/**
* Constructor of the object.
*/
public BookServlet() {
super();
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("书籍推荐:<br/>");
Map<String, Book> books = DBUtils.getBooks();
//遍历books
for (Map.Entry<String, Book> book:books.entrySet()) {
out.write("<a href='"+request.getContextPath()+"/servlet/BookDetailsServlet"
+ "?id="+book.getKey()+"'"+"target='_blank'"+">"+book.getValue().getName()+"</a><
4000
br>");

}

out.write("<hr/>最近浏览的书有:<br>");
Cookie[] cookies = request.getCookies();
//遍历cookies
for (int i = 0;cookies!=null&& i < cookies.length; i++) {
if("historyBookId".equals(cookies[i].getName())){
String value = cookies[i].getValue();//1-2-3
String[] ids = value.split("-");
//遍历ids
for (int j = 0; j < ids.length; j++) {
Book book = DBUtils.findBookById(ids[j]);
out.print(" "+book.getName());
}
}
}
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);

}

}





import entity.Book;
import utils.DBUtils;

public class BookDetailsServlet extends HttpServlet {

/**
* Constructor of the object.
*/
public BookDetailsServlet() {
super();
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//显示图书的详细信息

//获得id
String id=request.getParameter("id");
Book book = DBUtils.findBookById(id);
//          out.write(book.toString());
out.print(book);
//把当前浏览过的书的id写回客户端
String historyBookId=organizeId(id,request);
Cookie cookie=new Cookie("historyBookId", historyBookId);
cookie.setPath("/");
cookie.setMaxAge(Integer.MAX_VALUE);
response.addCookie(cookie);
}

/**
*
客户端                  BookServlet          BookDetailsServlet
1.没有cookie的情况          1                    historyBook=1
2.有cookie,但没有historyBook                    historyBook=1
3.historyBook=1          2                    historyBook=2-1
4.historyBook=1-2          2                    historyBook=2-2
5.historyBook=1-2-3     3               historyBook=2-1-3
6.historyBook=1-2-3     4               historyBook=4-1-2
*/

private String organizeId(String id, HttpServletRequest request) {
// TODO Auto-generated method stub
//得到客户端Cookie
Cookie[] cookies = request.getCookies();
if(cookies==null){
return id;
}
Cookie historyBook=null;
//遍历cookies
for (int i = 0; i < cookies.length; i++) {
if("historyBookId".equals(cookies[i].getName())){
historyBook=cookies[i];
}
}
//如果没有historyBookId的cookie,则返回id
if(historyBook==null){
return id;
}
String value = historyBook.getValue();
//切割组织的id
String[] values = value.split("-");
LinkedList<String> list=new LinkedList<String>(Arrays.asList(values));
//如果小于3本书
if(list.size()<3){
//如何集合中包含该id,则删除原来的id,将id重新加到first
if(list.contains(id)){
list.remove(id);
}
}else {
if(list.contains(id)){
list.remove(id);
}else {//如果已经有3个id了,则将集合的最后一个id删除
list.removeLast();
}
}
list.addFirst(id);//将最新的书添加到最前面
StringBuffer sb=new StringBuffer();
//遍历list,在id之间加上'-'
for (int i = 0; i < list.size(); i++) {
if(i>0){
sb.append("-");
}
sb.append(list.get(i));
}
System.out.println(sb);
return sb.toString();
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}





                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: