Java遇见HTML——JSP篇之商品浏览记录的实现
时间: 2023-08-01 10:10:05 浏览: 49
要实现商品浏览记录功能,可以使用JSP中的session对象来存储浏览过的商品信息。
首先,在商品详情页中,可以通过JSP代码获取到当前浏览的商品信息,并将其存储到session中。示例代码如下:
```
<%
String productId = request.getParameter("productId"); // 获取当前浏览的商品ID
String productName = "商品名称"; // 根据商品ID查询商品名称等信息
String productPrice = "商品价格";
String productImage = "商品图片路径";
// 将商品信息存储到session中
HttpSession session = request.getSession();
List<String[]> historyList = (List<String[]>) session.getAttribute("historyList");
if (historyList == null) {
historyList = new ArrayList<String[]>();
}
String[] productInfo = {productId, productName, productPrice, productImage};
historyList.add(0, productInfo);
if (historyList.size() > 5) {
historyList.remove(5);
}
session.setAttribute("historyList", historyList);
%>
```
上述代码中,首先获取到当前浏览的商品ID,然后查询该商品的名称、价格、图片路径等信息。接着,从session中获取商品浏览记录列表,如果列表不存在则创建一个新的列表。将当前浏览的商品信息添加到列表的最前面,如果列表超过了5个则删除最后一个。最后,将更新后的列表重新存储到session中。
在商品浏览记录页面中,可以通过JSP代码获取到session中存储的商品浏览记录列表,并将其展示出来。示例代码如下:
```
<%
HttpSession session = request.getSession();
List<String[]> historyList = (List<String[]>) session.getAttribute("historyList");
%>
<!DOCTYPE html>
<html>
<head>
<title>商品浏览记录</title>
</head>
<body>
<h1>商品浏览记录</h1>
<ul>
<% for (String[] productInfo : historyList) { %>
<li>
<a href="productDetail.jsp?productId=<%=productInfo[0]%>">
<img src="<%=productInfo[3]%>" alt="<%=productInfo[1]%>">
<span><%=productInfo[1]%></span>
</a>
</li>
<% } %>
</ul>
</body>
</html>
```
上述代码中,首先获取到session中存储的商品浏览记录列表。然后,使用JSP循环语句遍历列表中的每个商品信息,并将其展示出来。
以上就是实现商品浏览记录功能的JSP代码示例。需要注意的是,为了保证用户隐私安全,可能需要对商品浏览记录进行加密处理。