㈠ 在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>>购物车
</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存商品相关信息,包括数量,价格等。