文章目录 CartController CartMapper Cart DButil CartMapper.xml generatorConfig.xml mybatis-config.xml cart.jsp products.jsp(忽略) pom.xml
CartController
package controller ; 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. List ; @WebServlet ( urlPatterns = { "/cart/init" , "/cart/insert" , "/cart/delete" , "/cart/update" } )
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 . doUpdate ( req, resp) ; break ; } } private void doInit ( HttpServletRequest req, HttpServletResponse resp) throws ServletException , IOException { String realPath = req. getServletContext ( ) . getRealPath ( "/" ) ; System . out. println ( realPath) ; List < Cart > carts = mapper. selectAll ( ) ; req. setAttribute ( "list" , carts) ; req. getRequestDispatcher ( "/cart/cart.jsp" ) . forward ( req, resp) ; } private void doDel ( HttpServletRequest req, HttpServletResponse resp) throws IOException { int cartId = Integer . parseInt ( req. getParameter ( "cartId" ) ) ; mapper. deleteByPrimaryKey ( cartId) ; sqlSession. commit ( ) ; resp. sendRedirect ( req. getContextPath ( ) + "/cart/init" ) ; } private void doUpdate ( HttpServletRequest req, HttpServletResponse resp) throws IOException { Cart cart = new Cart ( ) ; int cartId = Integer . parseInt ( req. getParameter ( "cartId" ) ) ; int quantity = Integer . parseInt ( req. getParameter ( "quantity" ) ) ; int productId = Integer . parseInt ( req. getParameter ( "productId" ) ) ; cart. setCartId ( cartId) ; cart. setQuantity ( quantity) ; cart. setProductId ( productId) ; mapper. updateByPrimaryKey ( cart) ; sqlSession. commit ( ) ; resp. sendRedirect ( req. getContextPath ( ) + "/cart/init" ) ; } private void doInsert ( HttpServletRequest req, HttpServletResponse resp) throws IOException { Cart cart = new Cart ( ) ; int productId = Integer . parseInt ( req. getParameter ( "productId" ) ) ; int quantity = Integer . parseInt ( req. getParameter ( "quantity" ) ) ; cart. setProductId ( productId) ; cart. setQuantity ( quantity) ; int rows = 0 ; Cart cartResult = mapper. selectOneByProductId ( productId) ; if ( cartResult == null ) {
rows = mapper. insert ( cart) ; } else {
cartResult. setQuantity ( cartResult. getQuantity ( ) + 1 ) ; rows = mapper. updateByPrimaryKey ( cartResult) ; } sqlSession. commit ( ) ; if ( rows> 0 ) { resp. sendRedirect ( req. getContextPath ( ) + "/cart/init" ) ; } else { resp. sendError ( 500 , "添加异常" ) ; } } }
CartMapper
package mapper ; import java. util. List ;
import pojo. Cart ; public interface CartMapper { int deleteByPrimaryKey ( Integer cartId) ; int insert ( Cart row) ; Cart selectByPrimaryKey ( Integer cartId) ; List < Cart > selectAll ( ) ; int updateByPrimaryKey ( Cart row) ;
}
Cart
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
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 {
try { InputStream inputStream = Resources . getResourceAsStream ( "mybatis-config.xml" ) ; sqlSessionFactory = new SqlSessionFactoryBuilder ( ) . build ( inputStream) ;
} catch ( IOException e) { throw new RuntimeException ( e) ; } } public static SqlSession getSqlSession ( ) { return sqlSessionFactory. openSession ( ) ; } public static void close ( SqlSession session) { session. close ( ) ; } }
CartMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<! DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
< mapper namespace = " mapper.CartMapper" > < resultMap id = " BaseResultMap" type = " pojo.Cart" > < id column = " cart_id" jdbcType = " INTEGER" property = " cartId" /> < result column = " product_id" jdbcType = " INTEGER" property = " productId" /> < result column = " quantity" jdbcType = " INTEGER" property = " quantity" /> </ resultMap> < delete id = " deleteByPrimaryKey" parameterType = " java.lang.Integer" > delete from cartwhere cart_id = #{cartId,jdbcType=INTEGER}</ delete> < insert id = " insert" parameterType = " pojo.Cart" > insert into cart (cart_id, product_id, quantity)values (#{cartId,jdbcType=INTEGER}, #{productId,jdbcType=INTEGER}, #{quantity,jdbcType=INTEGER})</ insert> < update id = " updateByPrimaryKey" parameterType = " pojo.Cart" > update cartset product_id = #{productId,jdbcType=INTEGER},quantity = #{quantity,jdbcType=INTEGER}where cart_id = #{cartId,jdbcType=INTEGER}</ update> < select id = " selectByPrimaryKey" parameterType = " java.lang.Integer" resultMap = " BaseResultMap" > select cart_id, product_id, quantityfrom cartwhere cart_id = #{cartId,jdbcType=INTEGER}</ select> < select id = " selectAll" resultMap = " BaseResultMap" > select cart_id, product_id, quantityfrom cart</ select>
</ mapper>
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<! DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > < generatorConfiguration> < context id = " DB2Tables" targetRuntime = " MyBatis3Simple" > < plugin type = " org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" /> < commentGenerator> < property name = " suppressDate" value = " true" /> < property name = " suppressAllComments" value = " true" /> </ commentGenerator> < jdbcConnection driverClass = " com.mysql.cj.jdbc.Driver" connectionURL = " jdbc:mysql://localhost:3306/dict" userId = " root" password = " 123456" > </ jdbcConnection> < javaModelGenerator targetPackage = " pojo" targetProject = " src/main/java" > < property name = " enableSubPackages" value = " true" /> < property name = " trimStrings" value = " true" /> </ javaModelGenerator> < sqlMapGenerator targetPackage = " mapper" targetProject = " src/main/resources" > < property name = " enableSubPackages" value = " true" /> </ sqlMapGenerator> < javaClientGeneratortype = " xmlMapper" targetPackage = " mapper" targetProject = " src/main/java" > < property name = " enableSubPackages" value = " true" /> </ javaClientGenerator> < table tableName = " products" domainObjectName = " Products" /> < table tableName = " cart" domainObjectName = " Cart" /> </ context>
</ generatorConfiguration>
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> < 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" /> </ dataSource> </ environment> </ environments> < mappers> < mapper resource = " mapper/ProductsMapper.xml" /> < mapper resource = " mapper/CartMapper.xml" /> </ mappers>
</ configuration>
cart.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head><title>购物车</title><style>nav{display: flex;justify-content: space-between;/*将内部元素平均分布在容器内*/align-items: center;/*垂直居中*/}</style>
</head>
<body><h2>购物车</h2><%--el表达式,只能识别的就是域中值,从小到大默认找--%><c:forEach var="cart" items="${list}"><nav><li>${cart.productId}</li><li><a href="delete?cartId=${cart.cartId}">删除</a></li><li><%--修改数量--%><form action="update" method="post"><input type="number" name="quantity" value="${cart.quantity}" max="10"><input type="hidden" name="cartId" value="${cart.cartId}"><input type="hidden" name="productId" value="${cart.productId}"><input type="submit" value="修改数量"></form></li></nav></c:forEach>
</body>
</html>
products.jsp(忽略)
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head><title>商品列表</title><style>nav{display: flex;justify-content: space-between;/*将内部元素平均分布在容器内*/align-items: center;/*垂直居中*/}</style>
</head>
<body><h1>Product List</h1><%--java代码嵌套标签 {} --%><ul><c:forEach var="product" items="${requestScope.list}"><nav><%--集合都是默认解析的,list[index]--%><%--集合都是默认解析的,map[key]/map.key--%><%--javaBean的格式是默认解析的--%><li>${product.productName}</li><%--如果url中用/开头,那么链接时默认带上localhost:8080不带站点如果不以/开头,那么以当前的路径开始拼接,比如当前localhost:8080/mall/product--%><form action="/mall/cart/insert" method="post"><input type="hidden" name="productId" value="${product.productId}"><%-- <input type="number" name="quantity" value="">--%><input type="submit" οnclick="return confirmAdd()" value="加入购物车"></form><%-- <li>--%><%-- <%–get请求–%>--%><%-- <%– http://localhost:8080/mall/cart/insert –%>--%><%-- <a href="/mall/cart/insert?productId=${product.productId}">加入购物车</a>--%><%-- </li>--%></nav></c:forEach></ul></body>
</html>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
< 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/xsd/maven-4.0.0.xsd" > < modelVersion> 4.0.0</ modelVersion> < groupId> org.example</ groupId> < artifactId> web_tom3</ artifactId> < version> 1.0-SNAPSHOT</ version> < packaging> war</ packaging> < properties> < maven.compiler.source> 8</ maven.compiler.source> < maven.compiler.target> 8</ maven.compiler.target> < project.build.sourceEncoding> UTF-8</ project.build.sourceEncoding> </ properties> < build> < plugins> < plugin> < groupId> org.mybatis.generator</ groupId> < artifactId> mybatis-generator-maven-plugin</ artifactId> < version> 1.4.1</ version> < configuration> < overwrite> true</ overwrite> </ configuration> < dependencies> < dependency> < groupId> mysql</ groupId> < artifactId> mysql-connector-java</ artifactId> < version> 8.0.30</ version> </ dependency> </ dependencies> </ plugin> </ plugins> </ build> < dependencies> < 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> javax.servlet.jsp</ groupId> < artifactId> jsp-api</ artifactId> < version> 2.2</ version> < scope> provided</ scope> </ dependency> < dependency> < groupId> jstl</ groupId> < artifactId> jstl</ artifactId> < version> 1.2</ version> </ dependency> < dependency> < groupId> taglibs</ groupId> < artifactId> standard</ artifactId> < version> 1.1.2</ version> </ dependency> < dependency> < groupId> junit</ groupId> < artifactId> junit</ artifactId> < version> 4.13.2</ version> < scope> test</ scope> </ dependency> </ dependencies> </ project>