浏览器最近浏览记录

@WebServlet("/demo1")
public class Demo1 extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//得到所有的商品
ProService ps = new ProService();
Map map = ps.queryAll();
HttpSession session = req.getSession();
session.setAttribute("map", map);





//得到保存在cookie中的商品id(浏览过的)
List list = new ArrayList<>(); 
Cookie[] cookies = req.getCookies();
for (int i = 0; cookies!=null&&i < cookies.length; i++) {
if("history".equals(cookies[i].getName())) {
String value = cookies[i].getValue();
String[] split = value.split("-");
for (int j = 0; j < split.length; j++) {
//通过此id来找到商品
Product pro = ps.findPro(Long.parseLong(split[j]));
//存到集合中
list.add(pro);
}
}
}
session.setAttribute("hisList", list);

resp.sendRedirect("index.jsp");


@WebServlet("/demo2")
public class Demo2 extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//查看商品详细信息
String id = req.getParameter("id");
long id1 = Long.parseLong(id);
ProService ps= new ProService();
Product pro = ps.findPro(id1);
HttpSession session = req.getSession();
session.setAttribute("pro", pro);


//保存你浏览过的商品ID
String history = historyId(id, req);
Cookie c = new Cookie("history", history);
c.setMaxAge(60*60);
c.setPath("/");
resp.addCookie(c);
resp.sendRedirect("demo.jsp");



}
/*
* 刷新商品ID
*/
private String historyId(String id,HttpServletRequest req) {
Cookie[] cookies = req.getCookies();
if(cookies==null) {
return id;
}
Cookie history = null;
for (int i = 0; i < cookies.length; i++) {
if("history".equals(cookies[i].getName())) {
history = cookies[i];
}
}
if(history==null) {
return id;
}
String value = history.getValue();
String[] split = value.split("-");
LinkedList list = new LinkedList<>(Arrays.asList(split));
if(list.size()<3) {
if(list.contains(id)) {
list.remove(id);
}
}else {
if(list.contains(id)) {
list.remove(id);
}else {
list.removeLast();
}
}
list.addFirst(id);

StringBuffer sb = new StringBuffer();
for (int i = 0; i < list.size(); i++) {
if(i>0) {
sb.append("-");
}
sb.append(list.get(i));
}

return sb.toString();
}


数据显示
















idnamepricecount
${m.value.id}${m.value.name}${m.value.price}${m.value.count}



最近浏览



你还未浏览












name
${p.name}


你可能感兴趣的:(浏览器最近浏览记录)