❶ 如何用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;
}
}
有用請採納