07 购物车(dto)

2024-04-07 10:44
文章标签 07 购物车 dto

本文主要是介绍07 购物车(dto),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • products.sql
    • CartController.java
    • CartListDto.java
    • CartMapper.java
    • Cart.java
    • DButil.java
    • mybatis-config.xml
    • cart_list.html
    • pom.xml

从数据库products、cart两表中,处理得到所需数据,在购物车页面上显示

products.sql


create table products
(product_id       int auto_increment comment '产品ID'primary key,product_name     varchar(100)   null comment '产品名称',brand            varchar(50)    null comment '品牌',price            decimal(10, 2) null comment '价格',color            varchar(20)    null comment '颜色',storage_capacity varchar(10)    null comment '存储容量',description      text           null comment '描述'
)comment '手机产品表';

CartController.java

package controller;import com.alibaba.fastjson.JSON;
import dto.CartListDto;
import mapper.CartMapper;
import org.apache.ibatis.session.SqlSession;
import pojo.Cart;
import utils.DButil;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@WebServlet(urlPatterns = {"/cart/init","/cart/insert","/cart/delete","/cart/select","/cart/list"})
public class CartController extends HttpServlet {SqlSession sqlSession = DButil.getSqlSession();CartMapper mapper = sqlSession.getMapper(CartMapper.class);@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String servletPath = req.getServletPath();if (servletPath == null) {resp.sendError(404);}switch (servletPath) {case "/cart/init"://this.doInit(req, resp);break;case "/cart/insert"://this.doInsert(req, resp);break;case "/cart/delete"://this.doDel(req, resp);break;case "/cart/update"://this.doUpdata(req, resp);break;case "/cart/select":this.doGet(req, resp);break;case "/cart/list":this.doGetList(req, resp);break;}}private void doGetList(HttpServletRequest req, HttpServletResponse resp) {System.out.println("list is running...");List<CartListDto> cartListDtos = mapper.selectAllDto();for (CartListDto cartListDto : cartListDtos) {cartListDto.setTotal((cartListDto.getPrice() == null ? 0 : cartListDto.getPrice()) * cartListDto.getQuantity());}/** code状态码,200 404,500* msg 提示当前信息* data 我们要穿的值** */Map<String, Object> result = new HashMap<>();result.put("code", 200);if (cartListDtos == null || cartListDtos.size() <= 0) {result.put("mag", "查询异常");} else {result.put("msg", "成功");}result.put("data", cartListDtos);System.out.println(result.get("data"));//转为json字符串String jsonString = JSON.toJSONString(result);resp.setCharacterEncoding("UTF-8");try {resp.getWriter().write(jsonString);} catch (IOException e) {result.put("code", 500);result.put("msg", "失败");}}}

CartListDto.java


package dto;import java.io.Serializable;public class CartListDto implements Serializable {//    Product	Price	Quantity	TotalInteger cartId;String ProductName;Integer price;Integer quantity;Integer total;public CartListDto() {}@Overridepublic String toString() {final StringBuilder sb = new StringBuilder("CartListDto{");sb.append("cartId=").append(cartId);sb.append(", ProductName='").append(ProductName).append('\'');sb.append(", price=").append(price);sb.append(", quantity=").append(quantity);sb.append(", total=").append(total);sb.append('}');return sb.toString();}public CartListDto(Integer cartId, String productName, Integer price, Integer quantity) {this.cartId = cartId;ProductName = productName;this.price = price;this.quantity = quantity;this.total = this.price*this.quantity;}public Integer getCartId() {return cartId;}public void setCartId(Integer cartId) {this.cartId = cartId;}public String getProductName() {return ProductName;}public void setProductName(String productName) {ProductName = productName;}public Integer getPrice() {return price;}public void setPrice(Integer price) {this.price = price;}public Integer getQuantity() {return quantity;}public void setQuantity(Integer quantity) {this.quantity = quantity;}public Integer getTotal() {return total;}public void setTotal(Integer total) {this.total = total;}
}

CartMapper.java

package mapper;import dto.CartListDto;
import org.apache.ibatis.annotations.Select;
import pojo.Cart;import java.util.List;public interface CartMapper {int deleteByPrimaryKey(Integer cartId);int insert(Cart row);/*根据主键id,查数据*/Cart selectByPrimaryKey(Integer cartId);List<Cart> selectAll();int updateByPrimaryKey(Cart row);//根据商品名查购物车@Select("select * from cart where product_id = #{id}")Cart selectOneByProductId(Integer id);@Select("select c.cart_id,product_name,price,quantity from cart c left join products p on p.product_id = c.product_id")List<CartListDto> selectAllDto();
}

Cart.java

package pojo;public class Cart {private Integer cartId;private Integer productId;private Integer quantity;public Integer getCartId() {return cartId;}public void setCartId(Integer cartId) {this.cartId = cartId;}public Integer getProductId() {return productId;}public void setProductId(Integer productId) {this.productId = productId;}public Integer getQuantity() {return quantity;}public void setQuantity(Integer quantity) {this.quantity = quantity;}
}

DButil.java


package utils;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;
import java.io.InputStream;public class DButil {private static SqlSessionFactory sqlSessionFactory = null;//测试环境下的工厂private static SqlSessionFactory sqlSessionFactoryTest = null;static {//1.builder  一旦创建了 SqlSessionFactory,就不再需要它了
//        SqlSessionFactoryBuilder sqlSessionFactoryBuilder =//2.获取工厂// 获取资源 org.apache.ibatis.io.Resources;try {InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");//根据资源文件创建工厂sqlSessionFactory  = new SqlSessionFactoryBuilder().build(inputStream);//测试环境的创建工厂
//            sqlSessionFactoryTest  = new SqlSessionFactoryBuilder().build(inputStream,"testdevelopment");} catch (IOException e) {throw new RuntimeException(e);}}public static SqlSession getSqlSession(){//获得Sqlsessionreturn sqlSessionFactory.openSession();}public static void close(SqlSession session){session.close();}}

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><setting name="mapUnderscoreToCamelCase" value="true"/><!--        <setting name="cacheEnabled" value="true"/>--></settings><typeAliases><package name="pojo"/></typeAliases><!--    <typeAliases>--><!--        <typeAlias alias="Products" type="com.aistart.tech.pojo.Products"/>--><!--    </typeAliases>--><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/dict"/><property name="username" value="root"/><property name="password" value="123456"/><property name="poolMaximumActiveConnections" value="1"/></dataSource></environment><environment id="testdevelopment"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/dict?usessl=false"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><mappers><package name="mapper"/></mappers>
</configuration>

cart_list.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Shopping Cart</title><!--第一步引入jquery--><script src="/mall/js/jquery.min.js"></script><style>body {font-family: Arial, sans-serif;}table {width: 100%;border-collapse: collapse;}th, td {padding: 8px;border-bottom: 1px solid #ddd;text-align: left;}th {background-color: #f2f2f2;}</style>
</head>
<body><h2>我的购物车</h2><table><thead><tr><th>Product</th><th>Price</th><th>Quantity</th><th>Total</th><th>操作</th></tr></thead><tbody><!-- Add more rows as needed --></tbody><tfoot><tr><td colspan="3" style="text-align: right;">Total:</td><td></td></tr></tfoot>
</table><script>$(document).ready(initCart)function del(){let id = this.id;/*ajax删除*/$.get("del",{cartId:id},(data)=>{alert(data.msg);initCart();})}function initCart(){$.get("list",(data)=>{let result = JSON.parse(data);console.log(result)if (result.code==200){console.log(result.data);let cartList = result.data;for (let i = 0; i < cartList.length; i++) {let productName = cartList[i].productName;let price = cartList[i].price;let quantity = cartList[i].quantity;let total = cartList[i].total;let cartId = cartList[i].cartId;let strHtml = `<tr><td>${productName}</td><td>${price}</td><td>${quantity}</td><td>${total}</td><td><input type="button" id="${cartId}" value="删除" ></td></tr>`console.log(strHtml,document.querySelector("tbody"));document.querySelector("tbody").innerHTML+=strHtml;}}else {alert(result.msg);}})}</script></body>
</html>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>mall</artifactId><packaging>war</packaging><version>1.0-SNAPSHOT</version><name>mall Maven Webapp</name><url>http://maven.apache.org</url><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.48</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.15</version></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><version>8.0.31</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency></dependencies><build><finalName>mall</finalName></build>
</project>

这篇关于07 购物车(dto)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/882385

相关文章

07 v-if和v-show使用和区别

划重点: v-ifv-show 小葱拌豆腐 <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="

DTO类实现Serializable接口的重要性

所谓序列化,简单一点理解,就是将对象转换成字节数组,反序列化是将字节数组恢复为对象。凡是要在网络上传输的对象、要写入文件的对象、要保存到数据库中的对象都要进行序列化。Java对象是无法直接保存到文件中,或是存入数据库中的。如果要保存到文件中,或是存入数据库中,就要将对象序列化,即转换为字节数组才能保存到文件中或是数据库中。文件或者数据库中的字节数组拿出来之后要转换为对象才能被我们识别,即反序列化。

java基础总结07-面向对象3(this关键字)

this是一个引用,它指向自身的这个对象。 看内存分析图 假设我们在堆内存new了一个对象,在这个对象里面你想象着他有一个引用this,this指向这个对象自己,所以这就是this,这个new出来的对象名字是什么,我们不知道,不知道也没关系,因为这并不影响这个对象在内存里面的存在,这个对象只要在内存中存在,他就一定有一个引用this。 看下面的例子分析: package cn.ga

【SpringMVC学习07】SpringMVC与前台的json数据交互

json数据格式在接口调用中、html页面中比较常用,json格式比较简单,解析也比较方便,所以使用很普遍。在springmvc中,也支持对json数据的解析和转换,这篇文章主要总结一下springmvc中如何和前台交互json数据。 1. 两种交互形式  springmvc和前台交互主要有两种形式,如下图所示: 可以看出,前台传过来的方式有两种,一种是传json格式的数据过来,另一种

周末总结(2024/09/07)

工作 人际关系核心实践: `要学会随时回应别人的善意,执行时间控制在5分钟以内 坚持每天早会打招呼 遇到接不住的话题时拉低自己,抬高别人(无阴阳气息) 朋友圈点赞控制在5min以内,职场社交不要放在5min以外 职场的人际关系在面对利益冲突是直接质疑,要快准狠,不要内耗、 回复消息要控制在30mins之内,一定要及时回复`` 工作上的要点 现状(已经提了离职,last day在9月20号)

2024.09.07【读书笔记】| SMRTLink工具对PB组装疑难解答

在使用SMRT Link的pb_assembly_hifi命令进行组装分析时,可以参考以下步骤和信息: 使用pbcromwell show-workflow-details pb_assembly_hifi命令查看该工作流的详细信息。这将帮助你了解所需的输入参数和可选输入参数。 根据工作流的要求,你需要准备相应的输入文件。例如,对于单样本基因组组装,需要CCS(连续测序)的fastq文件路径作

【LeetCode】07.整数反转

题目要求 解题思路 这道题的难点在于怎么判断越界,我们无法直接与最大值或最小值比较,但是由于每一次我们的ret都需要乘10这个特性来使用ret与最大值或最小值除10进行比较 代码实现 class Solution {public:int reverse(int x) {int ret=0;while(x){//处理越界情况if(ret<INT_MIN/10||ret>INT_MAX

掌握Vuex:构建高效状态管理的购物车实例指南

Vuex 是 Vue.js 的官方状态管理库,它为 Vue 应用提供了一个集中存储所有组件状态的地方,并以相应的规则保证状态以一种可预测的方式发生变化。 1. 安装 Vuex 首先,需要安装 Vuex: npm install vuex --save 2. 创建 Store 在 Vue 项目中创建一个 store 文件夹,并在其中创建 index.js 文件: // store/in

【大数据Java基础-JAVA 面向对象07】类成员(二)类结构 方法(四)递归方法

1.定义: 递归方法:一个方法体内调用它自身。 2.如何理解递归方法? > 方法递归包含了一种隐式的循环,它会重复执行某段代码,但这种重复执行无须循环控制。 > 递归一定要向已知方向递归,否则这种递归就变成了无穷递归,类似于死循环。 3.举例: // 例1:计算1-n之间所自然数的和 public int getSum(int n) {// 3if (n == 1) {return 1;}

Kubernetes学习指南:保姆级实操手册07——calico安装、metric-server安装一、calico

七、Kubernetes学习指南:保姆级实操手册07——calico安装、metric-server安装 一、calico Calico是一个开源的虚拟化网络方案,支持基础的Pod网络通信和网络策略功能。 官方文档:Quickstart for Calico on Kubernetes | Calico Documentation 1、calico安装 ### 在Master控制节点执行