文章目录
从数据库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);
@Override
protected 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 Total
Integer cartId;
String ProductName;
Integer price;
Integer quantity;
Integer total;
public CartListDto() {
}
@Override
public 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(){
//获得Sqlsession
return sqlSessionFactory.openSession();
}
public static void close(SqlSession session){
session.close();
}
}
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//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>