毕业实习项目-12
作者:互联网
毕业实习项目-12
资源
链接: https://pan.baidu.com/s/1YvJ0sloV7E_d_I4Lqdnp4A .
提取码:kzpe
购物车-查看购物车
思路
前台:
- 新建shopping.jsp 文件(资源已给)
- top.jsp文件中修改购物车路径以及显示内容
- 循环遍历
<tr>
标签,显示购物车商品
后台:
1.新建一个ShoppingCart.java文件作为购物车Bean与ShoppingCartItem.java文件作为购物车商品单元Bean,两者放在po包下。
实操
- top.jsp文件中修改购物车路径以及显示内容
top.jsp文件相关代码
...
</c:if>
<!--用户已登陆-->
<c:if test="${!empty user }">
<!--修改购物车路径以及显示内容-->
<a href="shopping.jsp" class="shopping">购物车(${shoppingCart.shoppingCartItems == null ? 0 :shoppingCart。shoppingCartItems.size() })件商品</a>
<a href="user?action=userCenter">${user.userName }</a>
<!--用户注销-->
...
- 修改shopping.jsp 文件,循环遍历
<tr>
标签,显示购物车商品
shopping.jsp 文件相关代码
...
<th>购买数量</th>
<th>操作</th>
</tr>
<!-- 循环遍历`<tr>`标签 -->
<!-- 展示已添加的商品信息 -->
<c:forEach items="${shoppingCart.shoppingCartItems }" var="shoppingCartItem">
<tr class="productTr">
<td class="thumb"><!-- 产品图片与名称 -->
<img src="${shoppingCartItem.porduct.proPic }" class="imgs"/>
<a href="product?id=${shoppingCartItem.porduct.id }" >${shoppingCartItem.porduct.name }</a>
</td>
<td class="price"><!-- 单价 -->
<span>¥<label class="price_one" id="price_${shoppingCartItem.porduct.id }">${shoppingCartItem.porduct.price }</label></span>
</td>
<td class="price"><!-- 总价= 单价* 个数 -->
<span>¥<label id="productItem_total_${shoppingCartItem.porduct.id }">${shoppingCartItem.porduct.price*shoppingCartItem.count }</label></span>
</td>
<td class="number"><!--数量 -->
<input type="hidden" id="productId" value="${shoppingCartItem.porduct.id }"/>
<input type="button" value=" - " class="min"/>
<input type="text" value="${shoppingCartItem.count }" class="text_box" style="width:30px;text-align:center"/>
<input type="button" value=" + " class="add" />
</td>
<td class="delete"><!-- 删除 -->
<a href="javascript:removeShopping()">删除</a>
</td>
</tr>
</c:forEach>
</table>
<div class="button">
...
- ShoppingCart.java文件相关代码
...
/**
* 购物车Bean
* @author yu
*
*/
public class ShoppingCart {
private Integer userId;
private List<ShoppingCartItem> shoppingCartItems;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public List<ShoppingCartItem> getShoppingCartItems() {
return shoppingCartItems;
}
public void setShoppingCartItems(List<ShoppingCartItem> shoppingCartItems) {
this.shoppingCartItems = shoppingCartItems;
}
}
- ShoppingCartItem.java文件代码:
/**
* 购物车商品单元
* @author yu
*
*/
public class ShoppingCartItem {
private Product product;
private Integer count;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}
结果
经过以上步骤,登陆后通过点击购物车,购物车的初步显示功能就做好了。
购物车-添加购物车&点击购买
思路
前台:
- product.jsp中给放入购物车按钮修改链接路径,绑定JS方法
- JS中判断用户是登录,否,提示登陆;
- Ajax访问后台返回结果给回调函数 (result)
0:提示失败;1:刷新页面
后台:
- 新建一个ShoppingServlet
- detail.jsp文件中引入jquery
- 接收参数productId
- 非空判断
空,返回0 - 获取session中的购物车对象
- 对ShoppingCart进行非空判断
空:创建一个 - 获取shoppingCartItems
- 循环遍历shoppingCartItems
判断是否为同一商品;
是:count+1
不是:new一个shoppingCartItem,添加到shoppingCartItems里 - 覆盖session中的ShoppingCart
实操
- product.jsp中给放入购物车按钮修改链接路径,绑定JS方法
product.jsp文件相关代码
...
<p>库 存:${product.stock }</p>
<br/>
<div class="button">
<input type="button" name="button" value=""/><br/>
<!-- 给放入购物车按钮修改链接路径,绑定JS方法 -->
<a href="javascript:addShoppingCart(${product.id })">放入购物车</a>
</div>
</div>
<div class="clear"></div>
</div>
<div class="introduce">
<h2>
<strong>商品详情</strong>
</h2>
<div class="text">
${product.description }
</div>
</div>
</div>
<!-- 给放入购物车按钮绑定JS方法 -->
<script type="text/javascript">
function addShoppingCart(productId){
//JS中判断用户是登录;
if("${user.userName }" == ""){
//否,提示登陆;
alert("请登陆!")
return;
}
//Ajax访问后台返回结果给回调函数 (result)
$.ajax({
type:"post",
url:"shopping",
data:{
"action":"addShoppingCart",
"productId":productId
},
success: function(result){
if(result == 0){
//0:提示失败
alert("添加失败!");
}else{
//1:刷新页面
window.location.reload();
}
}
});
2.ShoppingServlet.java文件中写代码:
ShoppingServlet.java文件代码:
...
/**
* 购物车
* Servlet implementation class ShoppingServlet
*/
@WebServlet("/shopping")
public class ShoppingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ProductService productService = new ProductServiceImpl();
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String action = request.getParameter("action");
if("addShoppingCart".equals(action)){
//添加购物车
addShoppingCart(request,response);
}
}
/**
* 添加购物车
* @param request
* @param response
* @throws IOException
*/
private void addShoppingCart(HttpServletRequest request, HttpServletResponse response) throws IOException {
// TODO Auto-generated method stub
//接收参数productId
String productIdStr = request.getParameter("productId");
//非空判断
if(StringUtil.isEmpty(productIdStr)){
//空,返回0
response.getWriter().write("0");
return;
}
Integer productId = Integer.parseInt(productIdStr);
//获取session中的购物车对象
ShoppingCart shoppingCart = (ShoppingCart) request.getSession().getAttribute("shoppingCart");
//对ShoppingCart进行非空判断
if(shoppingCart == null){
//空:创建一个
shoppingCart = new ShoppingCart();
User user = (User) request.getSession().getAttribute("user");
shoppingCart.setUserId(user.getId());
}
//获取shoppingCartItems
List<ShoppingCartItem> shoppingCartItems = shoppingCart.getShoppingCartItems();
if(shoppingCartItems == null){
shoppingCartItems = new ArrayList<ShoppingCartItem>();
}
boolean flag = true;
//循环遍历shoppingCartItems
for (ShoppingCartItem shoppingCartItem : shoppingCartItems) {
//判断是否为同一商品;
if(shoppingCartItem.getProduct().getId() == productId){
//是:count+1
shoppingCartItem.setCount(shoppingCartItem.getCount() + 1);
flag = false;
break;
}
}
//不是:new一个shoppingCartItem,添加到shoppingCartItems里
if(flag){
Product product = productService.findProductById(productId);
ShoppingCartItem shoppingCartItem = new ShoppingCartItem();
shoppingCartItem.setProduct(product);
shoppingCartItem.setCount(1);
shoppingCartItems.add(shoppingCartItem);
}
shoppingCart.setShoppingCartItems(shoppingCartItems);
//覆盖session中的ShoppingCart
request.getSession().setAttribute("shoppingCart", shoppingCart);
//响应1
response.getWriter().write("1");
}
}
结果
这样,商品详情页面的添加购物车,和购买功能就做好了,当点击不同商品的添加购物车时,右上方的购物车里数量+1,点击购物车可以进入购物车页面查看自己的购物车里有哪些商品,点击购买时跳转购物车页面,并将要购买的商品添加到购物车里
图为点击放入购物车按钮:
图为相机商品详情:
图未点击购买(跳转至购物车页面):
购物车-购物车修改数量
思路
前台:
- shopping.jsp文件里发送Ajax请求到后台,传参productId、count
后台:
- ShoppingServlet
- 接收参数productId、count
- 非空判断
空:响应0
不为空:获取session中的购物车对象、shoppingCartItems
循环遍历shoppingCartItems
判断是否是这个商品
是:修改count; - 覆盖session中的shoppingCart
- 响应
实操
- 修改shopping.jsp文件
shopping.jsp文件相关代码
...
$("#productItem_total_" + product_id).html(price * t.val());
//重新计算全部商品的总价
setTotal();
updateShopping(1,product_id,t.val());
});
//对 " - "按钮进行操作
$(".min").click(function(){
//数量-1
var t= $(this).parent().find('input[class=text_box]');
t.val(parseInt(t.val()) - 1);
if(parseInt(t.val()) < 1){//不允许减少到1以下!
t.val(1);
}
//获取td隐藏域的id的值
var product_id = $(this).parent().find('input[id=productId]').val();
//获取对应ID的单价
var price = $("#price_" + product_id).html();
//修改该商品总价
$("#productItem_total_" + product_id).html(price * t.val());
//重新计算全部商品的总价
setTotal();
if(t.val() > 0){
updateShopping(0,product_id,t.val());
}
});
});
//添加减少购物车商品
function updateShopping(addOrCut,productId,count){
$.ajax({
type:"post",
url:"shopping",
data:{
"action":"updateShopping",
"productId":productId,
"count":count
},
success: function(result){
if(result == 0){
if(addOrCut == 0){
//减操作
$("#count").val(count + 1);
}else{
//加操作
$("#count").val(count - 1);
}
}
}
});
}
...
- ShoppingServlet.java文件代码
...
//添加购物车
addShoppingCart(request,response);
}else if("updateShopping".equals(action)){
//添加或减少购物车商品数量
updateShopping(request,response);
}
}
/**
* 添加或减少购物车商品数量
* @param request
* @param response
* @throws IOException
*/
private void updateShopping(HttpServletRequest request, HttpServletResponse response) throws IOException {
// TODO Auto-generated method stub
//接收参数productId、count
String countStr = request.getParameter("count");
String productIdStr = request.getParameter("productId");
//非空判断
if(StringUtil.isEmpty(productIdStr) || StringUtil.isEmpty(countStr)){
//空:响应0
response.getWriter().write("0");
return;
}
Integer productId =Integer.parseInt(productIdStr);
Integer count =Integer.parseInt(countStr);
//不为空:获取session中的购物车对象、shoppingCartItems
ShoppingCart shoppingCart = (ShoppingCart) request.getSession().getAttribute("shoppingCart");
List<ShoppingCartItem> shoppingCartItems = shoppingCart.getShoppingCartItems();
//循环遍历shoppingCartItems
for (ShoppingCartItem shoppingCartItem : shoppingCartItems) {
//判断是否是这个商品
if(shoppingCartItem.getProduct().getId() == productId){
//是:修改count;
shoppingCartItem.setCount(count);
break;
}
}
//覆盖session中的shoppingCart
request.getSession().setAttribute("shoppingCart", shoppingCart);
//响应
response.getWriter().write("1");
}
...
结果
经过以上的步骤,购物车内的商品增加减少小模块就做好了,通过点击+或者-小按钮可以同步在后台增加减少购物车里的商品数量。
购物车-购物车删除商品&结算
思路
前台:
一:删除商品:
- shopping.jsp中设置删除连接路径,绑定点击事件,传参productId
二:结算:
- 新建shopping-result.jsp页面(资源已给)
- shopping.jsp中设置结算提交表单的路径
后台:
一:删除商品:
- ShoppingServlet
- 接收参数productId
- 非空判断
空:响应0
不为空:获取session中的购物车对象、shoppingCartItems
循环遍历shoppingCartItems
判断是否是这个商品
是:移除 - 覆盖session中的shoppingCart
- 响应
二:结算:
- ShoppingServlet
- 获取session中的购物车对象
- 创建一个Order,设置userId,status,orderNo
- 获取shoppingCartItems
- 创建一个OrderProductList集合,
- 循环遍历shoppingCartItems
拿到每个商品的数量以及单价,计算当前商品总价
创建OrderProduct 设置productId num - 调用service进行添加订单(Order),返回新增的orderId
- 调用service进行添加order_product表信息(OrderProductList)
- 移除session中的购物车对象
- 跳转结算成功页面
实操
- shopping.jsp中设置删除连接路径,绑定点击事件,传参productId,设置结算提交表单的路径
shopping.jsp文件代码
...
您现在的位置:<a href="index">首页</a> > 购物车
</div>
<div id="main" class="wrap">
<div id="shopping">
<!-- 设置结算提交表单的路径 -->
<form action="shopping?action=settlement" method="post">
<table>
<tr>
<th>商品名称</th>
<th>商品单价</th>
</td>
...
...
...
<!-- 设置删除连接路径-->
<td class="delete"><!-- 删除 -->
<a href="javascript:removeShopping(${shoppingCartItem.product.id })">删除</a>
</td>
</tr>
</c:forEach>
</table>
<div class="button">
<input type="submit" value=""/>
...
...
...
//加操作
$("#count").val(count - 1);
}
}
}
});
}
function removeShopping(productId){
if(confirm("您确定要删除这个商品吗?")){
$.ajax({
type:"post",
url:"shopping",
data:{
"action":"deleteShopping",
"productId":productId,
},
success:function(result){
if(result == 0){
alert("网络异常!")
}else{
window.location.reload();
}
}
});
}
}
</script>
</html>
- ShoppingServlet文件里修改代码
ShoppingServlet文件代码
...
private static final long serialVersionUID = 1L;
private ProductService productService = new ProductServiceImpl();
private OrderService orderService = new OrderServiceImpl();
private OrderProductService orderProductService = new OrderProductServiceImpl();
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
...
...
...
//添加或减少购物车商品数量
updateShopping(request,response);
}else if("deleteShopping".equals(action)){
//删除商品
deleteShopping(request,response);
}else if("settlement".equals(action)){
//结算
settlement(request,response);
}
}
/**
* 结算
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void settlement(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//获取session中的购物车对象
ShoppingCart shoppingCart = (ShoppingCart) request.getSession().getAttribute("shoppingCart");
//创建一个Order,设置userId,status,orderNo
Order order = new Order();
order.setUserId(shoppingCart.getUserId());
order.setStatus(1);
order.setOrderNo(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()));
//获取shoppingCartItems
List<ShoppingCartItem> shoppingCartItems = shoppingCart.getShoppingCartItems();
//创建一个OrderProductList集合,
List<OrderProduct> orderProductList = new ArrayList<>();
float cost = 0;
//循环遍历shoppingCartItems
for (ShoppingCartItem shoppingCartItem : shoppingCartItems) {
//创建OrderProduct 设置productId num
OrderProduct orderProduct = new OrderProduct();
Integer count = shoppingCartItem.getCount();
orderProduct.setNum(count);
Product product = shoppingCartItem.getProduct();
orderProduct.setProductId(product.getId());
//拿到每个商品的数量以及单价,计算当前商品总价
Integer price = product.getPrice();
orderProductList.add(orderProduct);
cost += price*count;
}
order.setCost(cost);
//调用service进行添加订单(Order),返回新增的orderId
Integer orderId = orderService.addOrder(order);
//调用service进行添加order_product表信息(OrderProductList)
for (OrderProduct orderProduct : orderProductList) {
orderProduct.setOrderId(orderId);
orderProductService.addOrderProduct(orderProduct);
}
//移除session中的购物车对象
request.getSession().removeAttribute("shoppingCart");
//跳转结算成功页面
request.getRequestDispatcher("shopping-result.jsp").forward(request, response);
}
/**
* 删除商品
* @param request
* @param response
* @throws IOException
*/
private void deleteShopping(HttpServletRequest request, HttpServletResponse response) throws IOException {
// TODO Auto-generated method stub
//接收参数productId
String productIdStr = request.getParameter("productId");
//非空判断
if(StringUtil.isEmpty(productIdStr)){
//空:响应0
response.getWriter().write(0);
return;
}
Integer productId =Integer.parseInt(productIdStr);
//不为空:获取session中的购物车对象、shoppingCartItems
ShoppingCart shoppingCart = (ShoppingCart) request.getSession().getAttribute("shoppingCart");
List<ShoppingCartItem> shoppingCartItems = shoppingCart.getShoppingCartItems();
//循环遍历shoppingCartItems
for (ShoppingCartItem shoppingCartItem : shoppingCartItems) {
//判断是否是这个商品
if(shoppingCartItem.getProduct().getId() == productId){
//是:移除
shoppingCartItems.remove(shoppingCartItem);
break;
}
}
//覆盖session中的shoppingCart
request.getSession().setAttribute("shoppingCart", shoppingCart);
//响应
response.getWriter().write(1);
}
...
- OrderServiceImpl.java文件写功能代码
OrderServiceImpl.java文件新增代码
...
//添加订单
@Override
public Integer addOrder(Order order) {
// TODO Auto-generated method stub
Integer orderId = 0;
Connection conn = null;
//异常
try{
//数据库操作
//建立连接
conn = DBUtil.getConnection();
//编写sql语句
String sql = "insert into t_order (cost,createTime,orderNo,status,userId) values (?,now(),?,?,?);";
//new一个QueryRunner
QueryRunner qr = new QueryRunner();
Object[] params = {order.getCost(),order.getOrderNo(),order.getStatus(),order.getUserId()};
//执行添加
Long orderIdL = qr.insert(conn, sql, new ScalarHandler<>(), params);
orderId = orderIdL.intValue();
} catch (Exception e){
e.printStackTrace();
}finally{
//关闭连接
DBUtil.close(null, null, conn);
}
return orderId;
}
...
- OrderProductServiceImpl.java文件写功能代码
OrderProductServiceImpl.java文件文件新增代码
...
//添加OrderProduct
@Override
public void addOrderProduct(OrderProduct orderProduct) {
// TODO Auto-generated method stub
Connection conn = null;
//异常
try{
//数据库操作
//建立连接
conn = DBUtil.getConnection();
//编写sql语句
String sql = "insert into t_order_product (num,orderId,productId) values (?,?,?);";
//new一个QueryRunner
QueryRunner qr = new QueryRunner();
Object[] params = {orderProduct.getNum(),orderProduct.getOrderId(),orderProduct.getProductId()};
//执行添加
qr.update(conn,sql,params);
} catch (Exception e){
e.printStackTrace();
}finally{
//关闭连接
DBUtil.close(null, null, conn);
}
}
...
结果
写完了此小模块,整个项目就结束了,此处增加了购物车里删除商品的功能和商品结算功能,点击删除,就可以将购物车里想删除的商品进行删除操作,最后选好了商品我们可以进行结算,因为只是一个学习项目,点击结算按钮后做了一个结算成功页面,三秒后返回首页,没有支付环节,但是后台能生成订单,有总金额计算。那就,完结撒花咯!
可结算购物车页面
结算成功
后台数据库新增了一条结算后的订单信息(红框所示)
标签:count,12,毕业,request,购物车,shoppingCart,shoppingCartItems,实习,productId 来源: https://blog.csdn.net/weixin_42347543/article/details/114280515