浏览器最近浏览记录

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

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





//得到保存在cookie中的商品id(浏览过的)
List<Product> 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<String> 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();
}


数据显示

<table border="2">
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
<th>count</th>
</tr>
<c:forEach var="m" items="${map}">
<tr>
<td>${m.value.id}</td>
<td><a href="demo2?id=${m.value.id}">${m.value.name}</a></td>
<td>${m.value.price}</td>
<td>${m.value.count}</td>
</tr>
</c:forEach>
</table>
<hr>
<h3>最近浏览</h3>
<c:if test="${empty hisList}">
你还未浏览
</c:if>
<c:if test="${!empty hisList}">
<table>
<tr>
<th>name</th>
</tr>
<c:forEach var="p" items="${hisList}">
<tr>
<td>${p.name}</td>
</tr>
</c:forEach>

</table>
</c:if>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值