❶ 如何用java和jsp做一个简单的购物车
页面jsp :
<%@pagelanguage="java"contentType="text/html;charset=utf-8"
pageEncoding="utf-8"%>
<%@taglibprefix="c"uri="
<%@tagliburi="
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""
<htmlxmlns="
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>易买网-首页</title>
<linktype="text/css"rel="stylesheet"href="${pageContext.request.contextPath}/css/style.css"/>
<scripttype="text/javascript"src="${pageContext.request.contextPath}/js/jquery-2.1.1.js"></script>
<scripttype="text/javascript">
varcontextPath='${pageContext.request.contextPath}'
</script>
<scripttype="text/javascript"src="${pageContext.request.contextPath}/js/shopping.js"></script>
</head>
<body>
<jsp:includepage="top.jsp"/>
<divid="position"class="wrap">
您现在的位置:<ahref="Home">易买网</a>>购物车
</div>
<divclass="wrap">
<divid="shopping">
<formaction=""method="post">
<table>
<tr>
<th>商品名称</th>
<th>商品价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<c:forEachitems="${sessionScope.shopCar}"var="item"varStatus="status">
<trid="proct_id_${item.proId}">
<tdclass="thumb"><imgsrc="${item.proImg}"height="50"width="30"/><ahref="Proct?action=view&entityId=${item.proId}">${item.proName}</a></td>
<tdclass="price"id="price_id_1">
<span><fmt:formatNumbervalue="${item.proPrice}"type="NUMBER"minFractionDigits="2"/></span>
<inputtype="hidden"value="${item.proPrice}"/>
</td>
<tdclass="number">
<dl>
<dt><spanonclick="sub('number_id_${item.proId}','${item.proId}')">-</span><inputid="number_id_${item.proId}"type="text"readonly="readonly"name="number"value="${item.proNum}"/><spanonclick="addNum('number_id_${item.proId}','${item.proId}')">+</span></dt>
</dl>
</td>
<tdclass="delete"><ahref="javascript:deleteItem('proct_id_${item.proId}','${item.proId}')">删除</a></td>
</tr>
</c:forEach>
</table>
<divclass="button"><inputtype="submit"value=""/></div>
</form>
</div>
</div>
<divid="footer">
Copyright&;kaka292817678itjob远标培训.
</div>
</body>
</html>
页面关联的js 自己去网上下载一个jquery
/*数量减少*/
functionsub(id,proId){
//购买数量的值
varnum=$('#'+id).val();
if(num>1){
$('#'+id).val(num-1);
}
edit(id,proId);
}
functionedit(id,proId){
varurl=contextPath+'/HomeCarManager'
//修改后的数量,购物明细的商品的id
num=$('#'+id).val();
$.post(url,{"num":num,"proId":proId},function(msg){
/*
if(msg=='true'){
alert('修改成功');
}else{
alert('修改失败');
}*/
});
}
/**
*数量增加
*@param{}id
*/
functionaddNum(id,proId){
//购买数量的值
varnum=$('#'+id).val();
$('#'+id).val(parseInt(num)+1);
edit(id,proId);
}
/**
*删除购物明细
*/
functiondeleteItem(trId,proId){
//
//console.log($("#"+trId));
//js删除页面节点
//$("#"+trId).remove();
varurl=contextPath+'/HomeCarManager'
$.post(url,{"proId":proId},function(msg){
if(msg=='true'){
//js删除页面节点
$("#"+trId).remove();
}
});
}
后台servlet1
packagecom.kaka.web;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.ArrayList;
importjava.util.List;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
*购物车处理类
*@author@authorITJob远标培训
*
*/
importcom.kaka.entity.Items;
importcom.kaka.entity.Proct;
importcom.kaka.service.ProctService;
importcom.kaka.service.impl.ProctServiceImpl;
{
=1L;
ProctServiceps=newProctServiceImpl();
@Override
protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{
//获取商品的id
StringproId=req.getParameter("proId");
resp.setContentType("text/html;charset=UTF-8");
PrintWriterwriter=resp.getWriter();
if(null!=proId&&!"".equals(proId)){
//返回添加购物车成功
//System.out.println("============="+proId);
//根据商品的id查询商品
try{
IntegerpId=Integer.parseInt(proId);
Proctproct=ps.findProctById(pId);
if(null!=proct){
//查询到了商品,将商品的相关参数构建一个购物明细放入到购物车
Itemsit=newItems();
it.setProId(proct.getProId());
it.setProName(proct.getProName());
it.setProPrice(proct.getProPrice());
it.setProImg(proct.getProImg());
//先判断session范围是否有购物车
List<Items>shopCar=(List<Items>)req.getSession().getAttribute("shopCar");
if(null==shopCar){
//购物车
shopCar=newArrayList<Items>();
}
//将商品加入到购物车之前,判断购物车中是否已经包含了该购物明细,如果包含了,只需要修改购买的数量
if(shopCar.contains(it)){
intindex=shopCar.indexOf(it);//寻找购物车中包含购物明细在购物车中位置
Itemsitems=shopCar.get(index);//获取购物车中存在的购物明细
items.setProNum(items.getProNum()+1);
}else{
shopCar.add(it);
}
//将购物车放入到session访问
req.getSession().setAttribute("shopCar",shopCar);
//返回
writer.print(true);
}else{
writer.print(false);
}
}catch(Exceptione){
e.printStackTrace();
writer.print(false);
}
}else{
writer.print(false);
}
writer.flush();
writer.close();
}
@Override
protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{
doPost(req,resp);
}
}
后台管理servlet
packagecom.kaka.web;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.ArrayList;
importjava.util.List;
importjavax.mail.FetchProfile.Item;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
*购物车修改
*@authorITJob远标培训
*
*/
importcom.kaka.entity.Items;
importcom.kaka.entity.Proct;
importcom.kaka.service.ProctService;
importcom.kaka.service.impl.ProctServiceImpl;
{
=1L;
ProctServiceps=newProctServiceImpl();
@Override
protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{
resp.setContentType("text/html;charset=UTF-8");
PrintWriterwriter=resp.getWriter();
//获取参数
StringproId=req.getParameter("proId");
Stringnum=req.getParameter("num");
if(null!=proId&&null!=num
&&!"".equals(proId)&&!"".equals(num)){
try{
IntegerpId=Integer.parseInt(proId);
FloatpNum=Float.parseFloat(num);
//根据商品的id获取对应的明细项
//先判断session范围是否有购物车
List<Items>shopCar=(List<Items>)req.getSession().getAttribute("shopCar");
for(Itemsit:shopCar){
if(it.getProId()==pId){
it.setProNum(pNum);
}
}
writer.print(true);
}catch(Exceptione){
e.printStackTrace();
}
}else{
//删除的操作
try{
IntegerpId=Integer.parseInt(proId);
//根据商品的id获取对应的明细项
//先判断session范围是否有购物车
List<Items>shopCar=(List<Items>)req.getSession().getAttribute("shopCar");
Itemsitems=null;
for(Itemsit:shopCar){
if(it.getProId()==pId){
items=it;
break;
}
}
if(null!=items){
shopCar.remove(items);
req.getSession().setAttribute("shopCar",shopCar);
}
writer.print(true);
}catch(Exceptione){
e.printStackTrace();
}
}
writer.flush();
writer.close();
}
@Override
protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{
doPost(req,resp);
}
}
❷ Java初学者,哪位友友能帮我设计一个简单的类似超市购物车的程序,参考一下~谢谢!
以前学习java又做个实例,挺值得学习的。
1.首先我先列出我们所需要的java类结构。
1).java --------- 模拟存储商品的数据库。
2)McBean.java ------------ 商品实体类,一个普通的javabean,里面有商品的基本属性。
3)OrderItemBean.java --- 订单表。
4)ShoppingCar.java ------ 这个就是最主要的购物车,当然比较简单。
5)TestShoppingCar.java --- 这个是测试类。
2.下面贴出具体代码并带关键注释。
---Database.java
public class Database {
/*采用Map存储商品数据,为什么呢?我觉得这个问题你自己需要想下。
* Integer 为Map的key值,McBean为Map的value值。
*/
private static Map<Integer, McBean> data = new HashMap<Integer, McBean>();
public Database() {
McBean bean = new McBean();
bean.setId(1);
bean.setName("地瓜");
bean.setPrice(2.0);
bean.setInstuction("新鲜的地瓜");
data.put(1, bean);//把商品放入Map
bean = new McBean();
bean.setId(2);
bean.setName("土豆");
bean.setPrice(1.2);
bean.setInstuction("又好又大的土豆");
data.put(2, bean);//把商品放入Map
bean = new McBean();
bean.setId(3);
bean.setName("丝瓜");
bean.setPrice(1.5);
bean.setInstuction("本地丝瓜");
data.put(3, bean);//把商品放入Map
}
public void setMcBean(McBean mcBean){
data.put(mcBean.getId(),mcBean);
}
public McBean getMcBean(int nid) {
return data.get(nid);
}
}
---McBean.java
public class McBean {
private int id;//商品编号
private String name;//商品名
private double price;//商品价格
private String instuction;//商品说明
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getInstuction() {
return instuction;
}
public void setInstuction(String instuction) {
this.instuction = instuction;
}
}
---ShoppingCar.java
public class ShoppingCar {
private double totalPrice; // 购物车所有商品总价格
private int totalCount; // 购物车所有商品数量
private Map<Integer, OrderItemBean> itemMap; // 商品编号与订单项的键值对
public ShoppingCar() {
itemMap = new HashMap<Integer, OrderItemBean>();
}
public void buy(int nid) {
OrderItemBean order = itemMap.get(nid);
McBean mb;
if (order == null) {
mb = new Database().getMcBean(nid);
order = new OrderItemBean(mb, 1);
itemMap.put(nid, order);
update(nid, 1);
} else {
order.setCount(order.getCount() + 1);
update(nid, 1);
}
}
public void delete(int nid) {
OrderItemBean delorder = itemMap.remove(nid);
totalCount = totalCount - delorder.getCount();
totalPrice = totalPrice - delorder.getThing().getPrice() * delorder.getCount();
}
public void update(int nid, int count) {
OrderItemBean updorder = itemMap.get(nid);
totalCount = totalCount + count;
totalPrice = totalPrice + updorder.getThing().getPrice() * count;
}
public void clear() {
itemMap.clear();
totalCount = 0;
totalPrice = 0.0;
}
public void show() {
DecimalFormat df = new DecimalFormat("¤#.##");
System.out.println("商品编号\t商品名称\t单价\t购买数量\t总价");
Set set = itemMap.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {
OrderItemBean order = itemMap.get(it.next());
System.out.println(order.getThing().getId() + "\t"
+ order.getThing().getName() + "\t"
+ df.format(order.getThing().getPrice()) + "\t" + order.getCount()
+ "\t" + df.format(order.getCount() * order.getThing().getPrice()));
}
System.out.println("合计: 总数量: " + df.format(totalCount) + " 总价格: " + df.format(totalPrice));
System.out.println("**********************************************");
}
}
---OrderItemBean.java
public class OrderItemBean {
private McBean thing;//商品的实体
private int count;//商品的数量
public OrderItemBean(McBean thing, int count) {
super();
this.thing = thing;
this.count = count;
}
public McBean getThing() {
return thing;
}
public void setThing(McBean thing) {
this.thing = thing;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
---TestShoppingCar.java
package com.shop;
public class TestShoppingCar {
public static void main(String[] args) {
ShoppingCar s = new ShoppingCar();
s.buy(1);//购买商品编号1的商品
s.buy(1);
s.buy(2);
s.buy(3);
s.buy(1);
s.show();//显示购物车的信息
s.delete(1);//删除商品编号为1的商品
s.show();
s.clear();
s.show();
}
}
3.打印输出结果
商品编号 商品名称 单价 购买数量 总价
1 地瓜 ¥2 3 ¥6
2 土豆 ¥1.2 1 ¥1.2
3 丝瓜 ¥1.5 1 ¥1.5
合计: 总数量: ¥5 总价格: ¥8.7
**********************************************
商品编号 商品名称 单价 购买数量 总价
2 土豆 ¥1.2 1 ¥1.2
3 丝瓜 ¥1.5 1 ¥1.5
合计: 总数量: ¥2 总价格: ¥2.7
**********************************************
商品编号 商品名称 单价 购买数量 总价
合计: 总数量: ¥0 总价格: ¥0
**********************************************
4.打字太累了,比较匆忙,但是主要靠你自己领会。哪里不清楚再提出来。
❸ java购物车设计问题
取所选物品的id,每个id用逗号分开,存成一个字符串,在后台取的时候再把字符串中的逗回号去掉,答分成一个个的id就OK了!
JS:
var e=document.getElementsByTagName("input");
FORM.id.value="";
var j=0;
for(var i=0;i <e.length;i++)
{
if(e[i].type== "checkbox" && e[i].checked)
{
if(e[i].value!="hehe")
{
FORM.id.value=FORM.id.value+","+e[i].value;
j++;
}
}
}
后台:
if(ids!=null && !ids.equals("")){
//使用“,”分割字符串
ids=ids.trim().substring(1);
FieldTokenizer ft = new FieldTokenizer(ids, ",");
for(int j=0;j<ft.size();j++)
{
String id = ft.nextField();
}
那就把数量也逗号存里面
我没更好的方法了
跟你一起坐等高手解决
❹ java购物车类的设计
可选中1个或多个下面的关键词,搜索相关资料。也可直接点“搜索资料”搜索整个问题。
- 购物车
- java
- 设计
❺ 求java购物车例子。要用框架struts+hibernate+spring
java教程购物车Struts Hibernate实现shopcart
全部代码在
http://www.java125.cn/article.asp?id=1038
原理:利用会话保持用户一次购物操作的购买记录,当用户点击“结帐”后将保存在session中的hashmap容器中的信息insert到DB中,完成一次购物操作。
模块所需要配置文件:hibernate.cfg.xml ,TableGoods.hbm.xml ,struts-config.xml
模块对应的jsp有:index.jsp(商品信息一览页面),buy.jsp(购买操作后的商品清单页面)
模块对应的action有:IndexAction (实现对DB中的商品表信息结果集的遍历,并转向对应的index.jsp)
ListAction (将JSP上的商品信息存入hashmap容器,并转向对应的buy.jsp)
UpdateAction (对buy.jsp页面上的商品数量修改的业务逻辑处理)
DeleteAction (对buy.jsp页面上的商品列表信息的业务逻辑处理)
模块所需的相关Java容器选择:存储商品id,sum,price,name,allprices信息用hashmap,主要是考虑到其key重复后可以覆盖上次的value记录。存储点击商品后的商品id用list容器,主要考虑到list是有序并可以重复的特点,用其可以跟踪用户多次点击相同商品的操作,并对商品的数量进行相应的增加。
模块主要Action类如下:
IndexAction:
public class IndexAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
//查找商品表中的所有商品信息
GoodsDAO = new GoodsDAO();
List list = .find();
request.setAttribute("lister",list);
return mapping.findForward("a");
}
}
ListAction:
public class ListAction extends Action {
// 将hashmap中value转到list中
public static List getList(HashMap hs) {
List list = new ArrayList();
Iterator itr = hs.keySet().iterator();
while (itr.hasNext()) {
list.add(hs.get(itr.next()));
}
return list;
}
//优化后的getList方法
public static List getList(HashMap hs) {
return new ArrayList(hs.values());
}
全部代码在
http://www.java125.cn/article.asp?id=1038
❻ 关于java购物车设计的一些问题 1.支付完成如果断网了,怎样判断用户支付成功 2.如果购物车放
我想应该是购物车是放到cookie中的,需要结算的时候,登录后就会把cookie中的信息set到用户对象中.
❼ JAVA 购物车示例代码
import java.awt.*;
import java.awt.event.*;
class ShopFrame extends Frame implements ActionListener
{ Label label1,label2,label3,label4;
Button button1,button2,button3,button4,button5;
TextArea text;
Panel panel1,panel2;
static float sum=0.0f;
ShopFrame(String s)
{ super(s);
setLayout(new BorderLayout());
label1=new Label("面纸:3元",Label.LEFT);
label2=new Label("钢笔:5元",Label.LEFT);
label3=new Label("书:10元",Label.LEFT);
label4=new Label("袜子:8元",Label.LEFT);
button1=new Button("加入购物车");
button2=new Button("加入购物车");
button3=new Button("加入购物车");
button4=new Button("加入购物车");
button5=new Button("查看购物车");
text=new TextArea("商品有:"+"\n",5,10);
text.setEditable(false);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
panel1=new Panel();
panel2=new Panel();
panel1.add(label1);
panel1.add(button1);
panel1.add(label2);
panel1.add(button2);
panel1.add(label3);
panel1.add(button3);
panel1.add(label4);
panel1.add(button4);
panel2.setLayout(new BorderLayout());
panel2.add(button5,BorderLayout.NORTH);
panel2.add(text,BorderLayout.SOUTH);
this.add(panel1,BorderLayout.CENTER);
this.add(panel2,BorderLayout.SOUTH);
setBounds(100,100,350,250);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==button1)
{ text.append("一个面纸、");
sum=sum+3;
}
else if(e.getSource()==button2)
{ text.append("一只钢笔、");
sum=sum+5;
}
else if(e.getSource()==button3)
{ text.append("一本书、");
sum=sum+10;
}
else if(e.getSource()==button4)
{ text.append("一双袜子、");
sum=sum+8;
}
else if(e.getSource()==button5)
{
text.append("\n"+"总价为:"+"\n"+sum);
}
}
}
public class Shopping {
public static void main(String[] args) {
new ShopFrame("购物车");
}
}
我没用Swing可能显示不出来你的效果。不满意得话我在给你编一个。
❽ 用JAVA编写购物车程序.
我这有你要不?刚写的!
不过不是保存在内存上了,而是保存在数据库中,用完删不得了!
❾ java中购物车的功能怎么实现
session+cookie。先从cookie里读取上次的购物清单到session,本次添加的购物清单也将加入session。
❿ 求Java语言为书城设计一个简单购物车类。
public class ShoppingCart {//购物车类
private Procted prod;//商品类,存放商品信息
private int num;//商品数量
public Procted getProd() {
return prod;
}
public void setProd(Procted prod) {
this.prod = prod;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
public class Procted {//商品类
private String prodName;//商品名称
private Double marketPrice;//市场价
private Double sellPrice;//本店价
private Double save;//优惠
private Short points;//积分
public String getProdName() {
return prodName;
}
public void setProdName(String prodName) {
this.prodName = prodName;
}
public Double getMarketPrice() {
return marketPrice;
}
public void setMarketPrice(Double marketPrice) {
this.marketPrice = marketPrice;
}
public Double getSellPrice() {
return sellPrice;
}
public void setSellPrice(Double sellPrice) {
this.sellPrice = sellPrice;
}
public Double getSave() {
return save;
}
public void setSave(Double save) {
this.save = save;
}
public Short getPoints() {
return points;
}
public void setPoints(Short points) {
this.points = points;
}
}
有用请采纳