當前位置:首頁 » 網購平台 » jsp購物車代碼
擴展閱讀
寧波奧德賽優惠價格 2021-03-15 14:26:02
丹尼斯購物卡能掛失么 2021-03-15 14:25:58
淘寶購物指紋驗證失敗 2021-03-15 14:24:44

jsp購物車代碼

發布時間: 2021-01-01 03:08:27

㈠ 在JSP中怎樣實現購物車計數

問題比較怪異~
既然都會做購物車了~那麼計數又又什麼難的?
無非都是統計數字專罷了~
如果是問的購物車中總共又屬多少類商品,那麼只要統計集合中又多少個商品對象就可以了,用count或者size方法(視你所用集合而定)
如果問的是每類商品有多少個,那麼只要再再商品對象中加一個數量的屬性就OK了,無論增加或減小商品數量也只要修改這個屬性的值就可以~

㈡ 如何用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>&gt;購物車
</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);
}
}

㈢ 用jsp和資料庫做購物車,怎麼能通過點擊按鈕把購買數量和商品信息傳給購物車頁面,急!!下面是部分代碼

你把購買的數量和商品信息做成一個javabean,然後把這個javabean存在session裡面,你點擊按鈕就向伺服器端發出請求,然後伺服器端處理請求後用jsp顯示,這樣就可以了呀

㈣ jsp+mysql購物車示例

通過這個方抄法request.getsession().setAttribute("cart",購物車的數據);放入,然後需要提取的時候就通過request.getsession().getAttribute("cart");得到數據,然後在往資料庫裡面插就好了。

㈤ Jsp寫的購物車代碼

這是其中的一段代碼,要項目的話加445899710
HttpSession session = request.getSession(false);

if(session==null){
dispatcher = request.getRequestDispatcher("show.jsp");
dispatcher.forward(request, response);
}

FoodBean foodBean = (FoodBean)session.getAttribute("FoodToAdd");
Map cart = (Map)session.getAttribute("cart");

if(cart==null){
cart = new HashMap();
session.setAttribute("cart", cart);
}

CartItemBean cartItem = (CartItemBean)cart.get(foodBean.getFoodID());
if(cartItem==null){
cart.put(foodBean.getFoodID(), new CartItemBean(foodBean,1));
}else{
cartItem.setNumber(cartItem.getNumber()+1);
}

㈥ 求ejb+jsp實現簡單購物車功能的代碼

修改下述的例子,增加web功能

(1)提供登錄頁面Login.jsp;
只需要登錄名與密碼(可在程序中硬編碼)
(2)圖書列表頁面
列出所有可出售的圖書供用戶選擇;
圖書只需給出圖書名(可在程序中硬編碼)
(3)提供購物車商品的管理頁面:
能夠向購物車中添加圖書(從圖書列表中選擇);
能夠刪除購物車中的圖書;
能夠察看購物車中的圖書信息
(4)用戶可主動退出系統

一個EJB例子如下(購物車)
import java.util.*;
import javax.ejb.Stateful;
import javax.ejb.*;

@Stateful(mappedName="cart")
public class CartBean implements Cart{
String customerName;
String customerId;
List<String> contents;
//ArrayList<String> contents;

public void initialize(String person) throws BookException {
if (person == null) {
throw new BookException("不允許沒有用戶!");
} else {
customerName = person;
}
customerId = "0";
contents = new ArrayList<String>();
}

public void initialize(String person, String id)
throws BookException {
if (person == null) {
throw new BookException("不允許沒有用戶!");
} else {
customerName = person;
}
IdVerifier idChecker = new IdVerifier();
if (idChecker.validate(id)) {
customerId = id;
} else {
throw new BookException("無效的ID: " + id);
}
contents = new ArrayList<String>();
}

public void addBook(String title) {
contents.add(title);
}
public void removeBook(String title) throws BookException {
boolean result = contents.remove(title);
if (result == false) {
throw new BookException(title + " 不在購物車中。");
}
}
public List<String> getContents() {
return contents;
}
@Remove()
public void remove() {
contents = null;
}
}

㈦ jsp購物車的代碼和資料庫

//購物車類ShoppingCart,僅供參考
packagebookshop;
importjava.util.*;
importjava.sql.*;
importjava.text.*;
publicclassShoppingCart{
HashMapitems=null;
publicShoppingCart(){
items=newHashMap();
}
publicsynchronizedvoidadd(StringbookID)throwsException{
if(items.containsKey(bookID))
{
ShoppingCartItemitem=(ShoppingCartItem)items.get(bookID);
item.quantity++;
}
else
{
Stringsql="SELECT*FROMtb_BookWHEREbookID='"+bookID
+"'";
DBHandledbhandle=newDBHandle();
ResultSetrs=dbhandle.executeQuery(sql);
ShoppingCartItemnewItem=newShoppingCartItem();
if(rs.next()){
newItem.bookID=bookID;
newItem.isbn=rs.getString("ISBN");
newItem.bookName=rs.getString("bookName");
newItem.bookImage=rs.getString("bookImage");
newItem.categoryID=rs.getString("categoryID");
newItem.author=rs.getString("author");
newItem.price=rs.getFloat("price");
newItem.description=rs.getString("description");
newItem.quantity=1;
dbhandle.closeResource();
items.put(bookID,newItem);
}
}
}

publicsynchronizedvoidsetItem(StringBookID,intnum){
if(items.containsKey(BookID)){
ShoppingCartItemitem=(ShoppingCartItem)items.get(BookID);
item.quantity=num;
}
}

publicsynchronizedvoidremove(StringBookID){
items.remove(BookID);
}

(){
Collectionc=items.values();
returnc.iterator();
}

protectedvoidfinalize()throwsThrowable{
items.clear();
}

(){
returnitems.size();
}

(){
doubleamount=0.0;
for(Iteratori=getItems();i.hasNext();){
ShoppingCartItemitem=(ShoppingCartItem)i.next();
amount+=item.quantity*item.price;
}
returnroundOff(amount);
}

privatedoubleroundOff(doublex){
longval=Math.round(x*100);//cents
returnval/100;
}

publicsynchronizedvoidclear(){
items.clear();
}

publicintpayOrder(StringuserName,StringtrueName,Stringpostcode,
Stringaddress,Stringtelephone,Stringmemo)throwsException{
Connectionconn=null;
intorderID=0;
DBHandledbhandle=newDBHandle();
try{
conn=dbhandle.getConnection();
conn.setAutoCommit(false);

Statementstmt=conn.createStatement();
doubletotal=getTotal();
SimpleDateFormatdataFormat=newSimpleDateFormat(
"yyyy-MM-ddHH:mm:ss");
StringorderDate=dataFormat.format(newjava.util.Date());
Stringsql="INSERTINTOtb_Orders(userName,trueName,address,postcode,tel,memo,totalPrice,isPay,isDeliver,orderDate)VALUES('"
+userName+"','"+trueName
+"','"
+address
+"','"
+postcode
+"','"
+telephone
+"','"
+memo
+"',"
+total+",'0','0','"+orderDate+"')";
System.out.println(sql);
stmt.executeUpdate(sql);
sql="SELECTMAX(orderID)ASmaxOrderIDFROMtb_Orders";//改動
System.out.println(sql);
ResultSetrs=stmt.executeQuery(sql);
rs.next();
orderID=rs.getInt(1);
Iteratori=getItems();
while(i.hasNext()){
ShoppingCartItemitem=(ShoppingCartItem)i.next();
intquantity=item.quantity;
Stringid=item.bookID;
doubleprice=item.price;
sql="INSERTINTOtb_OrderDetail(orderID,bookID,quantity,price)VALUES("
+orderID
+","
+id
+","
+quantity
+","
+price
+")";
stmt.executeUpdate(sql);
}
conn.commit();
conn.setAutoCommit(true);
}catch(Exceptionex){
conn.rollback();
System.out.println(ex.getMessage());
throwex;
}finally{
dbhandle.closeResource();
}
returnorderID;
}
}
//圖書信息類,ShoppingCartItem
packagebookshop;
publicclassShoppingCartItem{
publicStringbookID=null;
publicStringisbn=null;
publicStringbookName=null;
publicfloatprice=0.0F;
publicStringdescription=null;
publicStringbookImage=null;
publicStringauthor=null;
publicStringcategoryID=null;
publicintquantity;
}

㈧ 求修改或者給我JSP購物車代碼

看看,能不能幫你:

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<jsp:directive.page import=".BookDao"/>
<jsp:directive.page import="entity.BookBean"/>
<html>
<head>
<title>詳細內容</title>
</head>
<%
List<BookBean> list=(List<BookBean>)session.getAttribute("list");
int size=list.size();
int bookId=Integer.parseInt(request.getParameter("bookid"));
BookBean book=null;
int i=0;
while(i<size){
book=list.get(i);
if(bookId==book.getBookId())
{
session.setAttribute("bookToAdd",book);
break;
}
i++;
}
%>
<body>
<center>
<h1><font color="red">書名;<%=book.getBookName() %></font></h1>
<h2>價格:<%=book.getPrice() %></h2>
<h2>描述:<%=book.getDescription() %></h2>
<form action="/book/AddBookToCart" method="post">
<input type="submit" value="放入購物車" ></form><input type="button" name="button2" value="查看購物車" onClick="window.location.href='cart.jsp'">
</center>
</body>
</html>

㈨ 怎麼用java代碼來實現jsp網頁里的購物車里的模塊

購物車都是存在cookie里的,一般不登陸都是可以加入購物車的。加入購物車就寫到cookie里就ok了。

㈩ jsp購物車是怎麼實現的,請具體解釋下,不要代碼,要用自己的話說

其實很簡單,就是復每次選擇制了商品之後保存起來就可以了
頁面的話可以將商品id用ajax傳給後台,而頁面要保存一個map,key是當前登錄用戶,從session中得到,value則是個list,list存商品相關信息,包括數量,價格等。