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>