易买网购物车结算用jsp怎么做

易买网购物车结算用jsp怎么做,第1张

页面jsp :

<%@ page language="java" contentType="text/html charset=utf-8"

    pageEncoding="utf-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html charset=utf-8" />

<title>易买网 - 首页</title>

<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/css/style.css" />

<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-2.1.1.js"></script>

<script type="text/javascript">

var contextPath = '${pageContext.request.contextPath }'

</script>

<script type="text/javascript" src="${pageContext.request.contextPath }/js/shopping.js"></script>

</head>

<body>

<jsp:include page="top.jsp" />

<div id="position" class="wrap">

您现在的位置:<a href="Home">易买网</a> &gt 购物

</div>

<div class="wrap">

<div id="shopping">

<form action="" method="post">

<table>

<tr>

<th>商品名称</th>

<th>商品价格</th>

<th>购买数量</th>

<th> *** 作</th>

</tr>

<c:forEach items="${sessionScope.shopCar}"  var="item" varStatus="status">

<tr id="product_id_${item.proId}">

<td class="thumb"><img src="${item.proImg }" height="50" width="30" /><a href="Product?action=view&entityId=${item.proId}">${item.proName}</a></td>

<td class="price" id="price_id_1">

<span><fmt:formatNumber value="${item.proPrice}" type="NUMBER" minFractionDigits="2" /></span>

<input type="hidden" value="${item.proPrice}" />

</td>

<td class="number">

<dl>

<dt><span onclick="sub('number_id_${item.proId}','${item.proId}')">-</span><input id="number_id_${item.proId}" type="text" readonly="readonly" name="number" value="${item.proNum}" /><span onclick="addNum('number_id_${item.proId}','${item.proId}')">+</span></dt>

</dl>

</td>

<td class="delete"><a href="javascript:deleteItem('product_id_${item.proId}','${item.proId}')">删除</a></td>

</tr>

</c:forEach>

</table>

<div class="button"><input type="submit" value="" /></div>

</form>

</div>

</div>

<div id="footer">

Copyright &copy  kaka qq 292817678 itjob  远标培训. 

</div>

</body>

</html>

页面关联的js 自己去网上下载一个jquery

/*数量减少*/

function sub(id,proId){

//购买数量的值

var num = $('#'+id).val()

if(num > 1){

$('#'+id).val(num - 1)

}

edit(id,proId)

}

function edit(id,proId){

var url = contextPath + '/HomeCarManager'

//修改后的数量,购物明细的商品的id

num = $('#'+id).val()

$.post(url,{"num":num,"proId":proId},function (msg){

/*

if(msg == 'true'){

alert('修改成功')

} else {

alert('修改失败')

}*/

})

}

/**

 * 数量增加

 * @param {} id

 */

function addNum(id,proId){

//购买数量的值

var num = $('#'+id).val()

$('#'+id).val(parseInt(num) + 1)

edit(id,proId)

}

/**

 * 删除购物明细

 */

function deleteItem(trId,proId){

//

//console.log($("#"+trId))

//js删除页面节点

//$("#"+trId).remove()

var url = contextPath + '/HomeCarManager'

$.post(url,{"proId":proId},function (msg){

if(msg == 'true'){

//js删除页面节点

$("#"+trId).remove()

}

})

}

后台servlet1

package com.kaka.web

import java.io.IOException

import java.io.PrintWriter

import java.util.ArrayList

import java.util.List

import javax.servlet.ServletException

import javax.servlet.http.HttpServlet

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

/**

 * 购物车处理类

 * @author @author ITJob 远标培训

 *

 */

import com.kaka.entity.Items

import com.kaka.entity.Product

import com.kaka.service.ProductService

import com.kaka.service.impl.ProductServiceImpl

public class HomeCar extends HttpServlet {

private static final long serialVersionUID = 1L

ProductService ps = new ProductServiceImpl()

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//获取商品的id

String proId = req.getParameter("proId")

resp.setContentType("text/htmlcharset=UTF-8")

PrintWriter writer = resp.getWriter()

if(null != proId && !"".equals(proId)){

//返回添加购物车成功

//System.out.println("=============" + proId)

//根据商品的id查询商品

try {

Integer pId = Integer.parseInt(proId)

Product product = ps.findProductById(pId)

if(null != product){

//查询到了商品,将商品的相关参数构建一个购物明细放入到购物车

Items it = new Items()

it.setProId(product.getProId())

it.setProName(product.getProName())

it.setProPrice(product.getProPrice())

it.setProImg(product.getProImg())

//先判断session范围是否有购物车

List<Items> shopCar = (List<Items>)req.getSession().getAttribute("shopCar")

if(null == shopCar){

//购物车

shopCar = new ArrayList<Items>()

}

//将商品加入到购物车之前,判断购物车中是否已经包含了该购物明细,如果包含了,只需要修改购买的数量

if(shopCar.contains(it)){

int index  = shopCar.indexOf(it)//寻找购物车中包含购物明细在购物车中位置

Items items = 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 (Exception e) {

e.printStackTrace()

writer.print(false)

}

} else {

writer.print(false)

}

writer.flush()

writer.close()

}

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doPost(req, resp)

}

}

后台管理servlet

package com.kaka.web

import java.io.IOException

import java.io.PrintWriter

import java.util.ArrayList

import java.util.List

import javax.mail.FetchProfile.Item

import javax.servlet.ServletException

import javax.servlet.http.HttpServlet

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

/**

 * 购物车修改

 * @author ITJob 远标培训

 *

 */

import com.kaka.entity.Items

import com.kaka.entity.Product

import com.kaka.service.ProductService

import com.kaka.service.impl.ProductServiceImpl

public class HomeCarManager extends HttpServlet {

private static final long serialVersionUID = 1L

ProductService ps = new ProductServiceImpl()

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

resp.setContentType("text/htmlcharset=UTF-8")

PrintWriter writer = resp.getWriter()

//获取参数

String proId = req.getParameter("proId")

String num = req.getParameter("num")

if(null != proId && null != num

&& !"".equals(proId) && !"".equals(num)){

try {

Integer pId = Integer.parseInt(proId)

Float pNum = Float.parseFloat(num)

//根据商品的id获取对应的明细项

// 先判断session范围是否有购物车

List<Items> shopCar = (List<Items>) req.getSession().getAttribute("shopCar")

for(Items it : shopCar){

if(it.getProId()== pId){

it.setProNum(pNum)

}

}

writer.print(true)

} catch (Exception e) {

e.printStackTrace()

}

} else {

//删除的 *** 作

try {

Integer pId = Integer.parseInt(proId)

//根据商品的id获取对应的明细项

// 先判断session范围是否有购物车

List<Items> shopCar = (List<Items>) req.getSession().getAttribute("shopCar")

Items items = null

for(Items it : shopCar){

if(it.getProId()== pId){

items = it

break

}

}

if(null != items){

shopCar.remove(items)

req.getSession().setAttribute("shopCar",shopCar)

}

writer.print(true)

} catch (Exception e) {

e.printStackTrace()

}

}

writer.flush()

writer.close()

}

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doPost(req, resp)

}

}

1、在手机淘宝店铺里,搜索查找到心仪的宝贝。

2、可以直接在宝贝页面点击购物车标志把宝贝加入购物车。

3、也可以点击进入宝贝详情页面,选择好宝贝后,点击加入购物车。

4、然后在购物车里可以勾选之前加入过购物车的心仪宝贝,可以勾选多个店铺的宝贝,选好后点击下面的【结算】。

5、点击结算后页面跳转到确认订单页面,可以查看购买的宝贝,然后提交订单确认付款。

购物车是电子商务网站中不可缺少的组成部分,但目前大多数购物车只能作为一个顾客选中商品的展示,客户端无法将购物车里的内容提取出来满足自己事务处理的需要,而这一点在有些电子商务活动中很有必要。XML的出现使得网络上传输的数据变得有意义起来,我们可以根据不同的要求以不同的样式将一个购物车的内容显示出来。

本文将详细分析一个由Java实现的基于XML的购物车。下面是一个包含了五件商品的购物车的XML内在结构:它的根元素为cart,total元素表示购物车内的总金额,每个item元素表示一件商品,item里的子元素分别标明了该商品的具体信息,可根据实际情况添加、修改或删除。

在这里,需要建立一个表示购物车的类:XMLCart.java,它是一个JavaBean,所以它包含了一个空的构造函数。这个类包含了购物车的一些基本功能: 生成一个空的购物车,往购物车里添加商品,删除购物车里的商品,改变购物车内商品的数量以及清空购物车等。它拥有一个全局私有变量“private XMLDocument myCart”,myCart用来存储购物车里的详细内容,购物车的基本功能就是对它的 *** 作,它的类型是XMLDocument,即一个XML文档。这样,对购物车的 *** 作就转换成对myCart中的子元素的添加、删除,及元素值的计算、修改等。

1. 清空购物车

清空购物车即生成一个空的购物车。这里空购物车是一个含有根元素cart及其元素total的XML文档,total元素是购物车的总金额,它的初始值为0,其XML具体形式如下:

<?xml version=‘1.0’ encoding=‘gb2312’?>

<cart>

<total>0</total>

</cart>

将这个XML字符串由parseString函数转换成XMLDocument存入myCart。

其代码如下:

public void emptyCart() throws IOException,SAXException{

String stringCart=“<?xml version=‘1.0’encoding=‘gb2312’?>”+

“<cart><total>0</total></cart>”

myCart=parseString(stringCart)

}

2. 添加商品

添加商品,即将传入的item元素添加到根元素cart里,

其中item里包括商品详细信息,

同时计算total的值。其代码如下:

public void addItemToCart(String stringItem)

throws IOException,SAXException{

//将item由String转换为XMLDocument

XMLDocument itemAdded=parseString(stringItem)

//取出item节点,并复制它

NodeList itemList=itemAdded.getElementsByTagName(“item”)

Node item=itemList.item(0)

Node cloneItem=item.cloneNode(true)

//如果购物车为空,则构造一个新的购物车

if(isCartEmpty()){

myCart.emptyCart()

}

//如果该商品不在购物车中,则插入该商品,并计算总金额

if(!isItemExist(item,myCart)){

//取myCart的根元素,并将复制的item节点添加到后面

Element cartRoot=myCart.getDocumentElement()

Node cartNode=cartRoot.appendChild(cloneItem)

computeTotal()//计算总金额

}

}

3. 删除商品

删除商品,即根据商品代码将该商品的item元素

从myCart的根元素cart中删除,

并重新计算total的值:

public void moveItemFromCart(String id){

//取出以item为单位的节点集cartList以及根元素cartRoot

NodeList cartList=myCart.getElementsByTagName(“item”)

Element cartRoot=myCart.getDocumentElement()

//在cartList中查找代码为选中id的商品

for(int x=0x<cartList.getLength()x++){

Node itemNode=cartList.item(x)

String idValue=itemNode.getFirstChild().

getFirstChild().getNodeValue()

//如果找到,则从cartRoot中删除该节点,并跳出循环

if(idValue.equals(id)){

itemNode=cartRoot.removeChild(itemNode)

break

}

}

computeTotal()//计算总金额

}

4. 改变商品数量

根据客户在页面上所填的数量,修改myCart中quantity,

并重新计算total:

public void addQuantityToCart(String qnty) throws

IOException,SAXException{

//将传过来的包含商品数量的一组XML字符串转换为XML文档

XMLDocument quantityChanged=parseString(qnty)

//取出包含新数量的quantity节点集和myCart中的quantity节点集

NodeList quantityList=quantityChanged.getElementsByTagName(“quantity”)

NodeList cartList=myCart.getElementsByTagName(“quantity”)

//循环改变商品的数量

for(int x=0x<cartList.getLength()x++){

//将新quantity的值赋给myCart中相应的quantity中去

String quantity=quantityList.item(x).getFirstChild().getNodeValue()

cartList.item(x).getFirstChild().setNodeValue(quantity)

}

computeTotal()//计算总金额

}

5. 计算总金额

即计算total的值,其中total=∑(price*quantity):

public void computeTotal(){

NodeList quantityList=myCart.getElementsByTagName(“quantity”)

NodeList priceList=myCart.getElementsByTagName(“price”)

float total=0

//累加总金额


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/bake/11327898.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-15
下一篇2023-05-15

发表评论

登录后才能评论

评论列表(0条)

    保存