JSP-----------简易购物车代码

第一步:显示界面


<%@page import="web.model.Proc"%>
<%@ page  contentType="text/html;charset=GBK" pageEncoding="GBK" import="java.util.*"  %>
<html>
<body>
<h1>商品列表页面,访问次数:<%=application.getAttribute("count")==null?1:application.getAttribute("count") %></h1>
<%

List<Proc> list = new ArrayList();
for(int i=0;i<10;i++){
Proc p =new Proc();
p.setId(i);
p.setPrice(i+5);
p.setProcName("procName"+i);
list.add(p);
}
%>


<table border="1" cellspacing="0" width="70%">
<tr>
<th>Id</th>
<th>Name</th>
<th>Price</th>
<th>Op</th>
</tr>
<%
for(int i=0;i<list.size();i++){
%>
<tr>
<td><%=list.get(i).getId() %></td>
<td><%=list.get(i).getProcName() %></td>
<td><%=list.get(i).getPrice() %></td>
<td> <a href="add.jsp?id=<%=list.get(i).getId() %>">添加购物车</a></td>
</tr>
<%
}
%>
</table>
<a href="query.jsp">查看购物车</a>


<%
if(application.getAttribute("count")==null){
application.setAttribute("count","1");
}else{
application.setAttribute("count",Integer.parseInt(application.getAttribute("count")+"")+1+"");
}
%> 
</body>
</html>




第二步:创建java部分,1,3,4部分都属于jsp部分。

package web.model;


public class Proc {
private Integer id;
private String  procName;
private Integer price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProcName() {
return procName;
}
public void setProcName(String procName) {
this.procName = procName;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}

}


第三步:添加提示界面

<%@page import="web.model.Proc"%>
<%@ page  contentType="text/html;charset=GBK" pageEncoding="GBK" import="java.util.*"  %>
<html>
<body>
<%
// 思路 把商品添加到map结构里面, 再把map添加到session里面
// 添加到购物车的商品id
String idStr = request.getParameter("id");
Integer id = new Integer(idStr);
Map<Integer,Integer> map = (Map<Integer,Integer>)session.getAttribute("map");
if(map==null){
map = new HashMap<Integer,Integer>();


Integer value = map.get(id);
if(value==null){
map.put(id, 1);
}else{
map.put(id, value+1);
}

session.setAttribute("map", map);

out.println("添加成功!<A href='procList.jsp'>返回</a>");
%>
</body>
</html>


第四步:物品显示界面

<%@page import="web.model.Proc"%>
<%@ page  contentType="text/html;charset=GBK" pageEncoding="GBK" import="java.util.*"  %>
<html>
<body>
<%
Map<Integer, Integer> map = (Map) session.getAttribute("map");
Set<Integer> set = map.keySet();
for(Integer i : set){
out.println("商品id:"+i+",购买数量:"+map.get(i)+"<br>");
}
out.println("商品添加成功!<A href='procList.jsp'>返回</a>");
%>
</body>
</html>



以上属于课堂笔记。版权归老师所有。要美化还需诸君DIY。  希望对大家有帮助。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值