list.jsp
<body>
<h1>淘寶商品列表</h1>
<table>
<tr>
<td>
<a href="/session-cart/details.jsp"><img src="/session-cart/img/1.jpg" height="200" width="200"></a><br>
Girl<br>
Total:1125件<br>
¥1050.00<br>
<a href ="/session-cart/AServlet?name=0" >Add to cart</a>
</td>
<td>
<img src="/session-cart/img/2.jpg" height="200" width="200"><br>
Lady<br>
Total:1125件<br>
¥1050.00<br>
<a href ="/session-cart/AServlet?name=1">加入購物車</a>
</td>
</tr>
<tr>
<td>
<img src="/session-cart/img/3.jpg" height="200" width="200"><br>
Cool<br>
<a href ="/session-cart/AServlet?name=2">加入購物車</a>
</td>
<td>
<img src="/session-cart/img/4.jpg" height="200" width="200"><br>
Sex<br>
<a href ="/session-cart/AServlet?name=3">加入購物車</a>
</td>
</tr>
</table>
<a href="/session-cart/cart.jsp">查看購物車</a>
</body>
AServlet.java
public class AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String index = request.getParameter("name");
String[] clothes = { "Girl", "Lady", "Cool", "Sex" };
String name = clothes[Integer.parseInt(index)];
Map<String, Integer> cartMap = (Map<String, Integer>) request
.getSession().getAttribute("cart");
if (cartMap == null) {
cartMap = new LinkedHashMap<String, Integer>();
request.getSession().setAttribute("cart", cartMap);
}
Integer count = cartMap.put(name, 1);
if (count != null) {
cartMap.put(name, count + 1);
}
response.sendRedirect("/session-cart/list.jsp");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
cart.jsp
<body>
<h1>購物車</h1>
<table>
<tr>
<th>商品名稱</th>
<th>商品數量</th>
<th>商品價格</th>
</tr>
<%
Map<String,Integer>map = (Map<String,Integer>)request.getSession().getAttribute("cart");
if(map!=null&&map.size()>0){
for(Entry<String,Integer>en:map.entrySet()){
%>
<tr>
<th><%=en.getKey()%></th>
<th><%=en.getValue() %></th>
</tr>
<%
}
}
%>
</table>
<h4>合計:</h4>
</body>
details.jsp用於顯示點擊圖片以後的內容,自己弄吧。