Online shopping system based on Spring MVC + Spring + MyBatis

Keywords: Java MySQL MyEclipse Spring mvc

Resource download: https://download.csdn.net/download/weixin_44893902/45601185

Exercise point design: modify, delete

1, Language and environment

  1. Implementation language: JAVA language.
  2. Environment requirements: MyEclipse/Eclipse + Tomcat + MySql.
  3. Use technology: Jsp+Servlet+JavaBean or spring MVC + Spring + mybatis.

2, Realize function

With more and more online shopping and more electronic orders, there is a special need for online shopping system:
1. The home page displays all order information by default, as shown in the figure.

2. Correctly display the order status and corresponding operations: 1. Place an order, and the operation is "ship and delete"; 2 is shipped, and the operation is "confirm harvest and delete"; 3 is received, and the only operation is "delete", as shown in the figure.

Figure 2 order status and corresponding operations
3. When the user clicks delete, a prompt box will pop up. After the user clicks OK, the selected data will be deleted and the latest data will be displayed, as shown in the figure.

4. The user clicks the "shipment" operation link to modify the order information in the database, and the page jumps to the list page to display the latest data, as shown in the figure.

5. The user clicks the "confirm receipt" operation link to modify the order information in the database, and the page jumps to the list page to display the latest data, as shown in the figure.

3, Specific requirements and recommended implementation steps

  1. The implementation steps of JSP version are as follows:
    (1) Build database and tables according to the above database requirements, and add test data.
    (2) Create a Web project, create various packages, and import the jar files required by the project.
    (3) Create an entity class.
    (4) Create a Servlet to obtain different requests from users, and forward these requests to the corresponding business methods of the business processing layer.
    (5) Create a business processing layer in which business methods are defined to implement system requirements, in which DAO methods need to be executed.
    (6) Create a BaseDAO tool class and use JDBC to complete the query, deletion and addition of data table data.
    (7) Write JSP pages to display the query results of data.

  2. The implementation steps of SSM version are as follows:
    (1) Create database and data table and add test data (add at least 5 test data).
    (2) Create a Web project, create various packages, and import the jar files required by the project.
    (3) Add relevant SSM framework support.
    (4) Various configuration files required by the configuration project (mybatis configuration file, spring configuration file, spring MVC configuration file).
    (5) Create an entity class.
    (6) Mapper interface required to create MyBatis operation database and its Xml mapping database operation statement file.
    (7) Create corresponding interfaces and implementation classes of business logic, implement corresponding businesses, and add references and injections to DAO/Mapper in the classes.
    (8) Create the Controller class, add reference and injection to the business logic class in the Controller, and configure the spring MVC configuration file.
    (9) Create relevant operation pages and beautify the pages with CSS.
    (10) Realize various operation functions of the page and verify them in relevant places. The operation should be humanized.
    (11) After debugging and running successfully, export relevant database files and submit them.

4, Database design

1. Create a database (Shops).
2. Create a data table (shop_db) with the following structure.

/*
Date: 06/08/2021 19:33:22
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for tb_dever
-- ----------------------------
DROP TABLE IF EXISTS `tb_dever`;
CREATE TABLE `tb_dever`  (
  `dev_id` int(11) NOT NULL AUTO_INCREMENT,
  `dev_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `dev_level` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `dev_work_year` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `dev_in_year` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`dev_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of tb_dever
-- ----------------------------
INSERT INTO `tb_dever` VALUES (1, 'Zhang San', 'senior', '40', '2021-08-02');
INSERT INTO `tb_dever` VALUES (2, 'Li Si', 'senior', '25', '2021-07-28');
INSERT INTO `tb_dever` VALUES (3, 'Wang Wu', 'intermediate', '40', '2020-11-13');
INSERT INTO `tb_dever` VALUES (4, 'Li Mei', 'senior', '35', '2021-05-12');
INSERT INTO `tb_dever` VALUES (5, 'Yang Qi', 'intermediate', '28', '2021-07-16');

SET FOREIGN_KEY_CHECKS = 1;

2. Project Java code

directory structure
Shops

JAR package:

src

com.controller

ShopController.java

package com.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.entity.TbOrder;
import com.service.impl.ShopService;

@Controller
public class ShopController {
	@Resource
	ShopService shoppService;

	@RequestMapping("/selectAll")
	// Query all orders
	public String shooplist(Model model) {
		List<TbOrder> selectAll = shoppService.selectAll();
		model.addAttribute("selectAll", selectAll);
		return "/shopOrder";
	}

	// Order changed from ordered 1 to shipped 2
	@RequestMapping("/update1b2")
	public String updateShopp1b2(int id) {
		int updateShop = shoppService.update1b2(id);
		return "redirect:/selectAll.do";
	}

	// Order changed from shipped 2 to received 3
	@RequestMapping("/update2b3")
	public String updateShopp2b3(int id) {
		int updateShop = shoppService.update2b3(id);
		return "redirect:/selectAll.do";
	}

	// Delete order
	@RequestMapping("/del")
	public String deleteShopp(int id) {
		int deldeteShopp = shoppService.del(id);
		return "redirect:/selectAll.do";
	}
}

com.dao

TbOrderMapper.java

package com.dao;

import java.util.List;

import com.entity.TbOrder;

public interface TbOrderMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(TbOrder record);

    TbOrder selectByPrimaryKey(Integer id);

    List<TbOrder> selectAll();

    int updateByPrimaryKey(TbOrder record);
    
    int update1b2(int id);
    
    int update2b3(int id);
}

TbOrderMapper.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="com.dao.TbOrderMapper">
	<resultMap id="BaseResultMap" type="com.entity.TbOrder">
		<id column="id" property="id" jdbcType="INTEGER" />
		<result column="goodName" property="goodname" jdbcType="VARCHAR" />
		<result column="goodPrice" property="goodprice" jdbcType="VARCHAR" />
		<result column="count" property="count" jdbcType="INTEGER" />
		<result column="total" property="total" jdbcType="VARCHAR" />
		<result column="orderDate" property="orderdate" jdbcType="VARCHAR" />
		<result column="userName" property="username" jdbcType="VARCHAR" />
		<result column="state" property="state" jdbcType="VARCHAR" />
	</resultMap>
	<delete id="del" parameterType="java.lang.Integer">
		delete from tb_order
		where id = #{id,jdbcType=INTEGER}
	</delete>
	<insert id="insert" parameterType="com.entity.TbOrder">
		insert into tb_order (id, goodName, goodPrice,
		count, total, orderDate,
		userName, state)
		values (#{id,jdbcType=INTEGER}, #{goodname,jdbcType=VARCHAR},
		#{goodprice,jdbcType=VARCHAR},
		#{count,jdbcType=INTEGER}, #{total,jdbcType=VARCHAR}, #{orderdate,jdbcType=VARCHAR},
		#{username,jdbcType=VARCHAR}, #{state,jdbcType=VARCHAR})
	</insert>
	<update id="updateByPrimaryKey" parameterType="com.entity.TbOrder">
		update tb_order
		set goodName = #{goodname,jdbcType=VARCHAR},
		goodPrice = #{goodprice,jdbcType=VARCHAR},
		count = #{count,jdbcType=INTEGER},
		total = #{total,jdbcType=VARCHAR},
		orderDate = #{orderdate,jdbcType=VARCHAR},
		userName = #{username,jdbcType=VARCHAR},
		state = #{state,jdbcType=VARCHAR}
		where id = #{id,jdbcType=INTEGER}
	</update>
	<select id="selectByPrimaryKey" resultMap="BaseResultMap"
		parameterType="java.lang.Integer">
		select id, goodName, goodPrice, count, total, orderDate, userName, state
		from tb_order
		where id = #{id,jdbcType=INTEGER}
	</select>
	<select id="selectAll" resultMap="BaseResultMap">
		select id, goodName, goodPrice, count, total, orderDate, userName, state
		from tb_order
	</select>
	<update id="update1b2" parameterType="com.entity.TbOrder">
		update tb_order
		<trim prefix="set" suffixOverrides=",">
			<if test="state=1">
				state=2,
			</if>

		</trim>
		where id = #{id,jdbcType=INTEGER}
	</update>
	<update id="update2b3" parameterType="com.entity.TbOrder">
		update tb_order
		<trim prefix="set" suffixOverrides=",">

			<if test="state=2">
				state=3,
			</if>
		</trim>
		where id = #{id,jdbcType=INTEGER}
	</update>
</mapper>

com.entity

TbOrder.java

package com.entity;

public class TbOrder {
    private Integer id;

    private String goodname;

    private String goodprice;

    private Integer count;

    private String total;

    private String orderdate;

    private String username;

    private String state;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getGoodname() {
        return goodname;
    }

    public void setGoodname(String goodname) {
        this.goodname = goodname == null ? null : goodname.trim();
    }

    public String getGoodprice() {
        return goodprice;
    }

    public void setGoodprice(String goodprice) {
        this.goodprice = goodprice == null ? null : goodprice.trim();
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total == null ? null : total.trim();
    }

    public String getOrderdate() {
        return orderdate;
    }

    public void setOrderdate(String orderdate) {
        this.orderdate = orderdate == null ? null : orderdate.trim();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state == null ? null : state.trim();
    }
}

com.service.impl

ShopService.java

package com.service.impl;

import java.util.List;

import com.entity.TbOrder;

public interface ShopService {
	//Query all
	List<TbOrder> selectAll();
	// Order changed from ordered 1 to shipped 2
	int update1b2(int id);
	// Order changed from shipped 2 to received 3
	int update2b3(int id);
	// Delete order
	int del(Integer id);
}

ShopServiceImpl.java

package com.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.dao.TbOrderMapper;
import com.entity.TbOrder;
@Service
public class ShopServiceImpl implements ShopService {
	
	@Resource
	TbOrderMapper mapper;
	// Query all orders
	@Override
	public List<TbOrder> selectAll() {
		List<TbOrder> listShopp=mapper.selectAll();
		return listShopp;
	}
	// Delete order
	@Override
	public int del(Integer id) {
		int deleteShoop=mapper.deleteByPrimaryKey(id);
		return deleteShoop;
	}
	// Order changed from ordered 1 to shipped 2
	@Override
	public int update1b2(int id) {
		int updateshopp=mapper.update1b2(id);
		return updateshopp;
	}
	// Order changed from shipped 2 to received 3
	@Override
	public int update2b3(int id) {
		int updateshopp1=mapper.update2b3(id);
		return updateshopp1;
	}

}

MyBatis

SqlMapConfig.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>
<!-- alias -->
	<typeAliases>
		<package name="com.entity"/>
	</typeAliases>
</configuration>

spring

applicationContext-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		xmlns="http://www.springframework.org/schema/beans" 
		xmlns:context="http://www.springframework.org/schema/context" 
		xmlns:aop="http://www.springframework.org/schema/aop" 
		xmlns:tx="http://www.springframework.org/schema/tx" 
		xmlns:mvc="http://www.springframework.org/schema/mvc" 
		xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd ">
		<context:property-placeholder location="classpath:dataSource.properties"/>
		<!-- Data source configuration -->
		<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
			<property name="driverClassName" value="${db.driverClass}"></property>
			<property name="Url" value="${db.jdbcUrl}"></property>
			<property name="username" value="${db.user}"></property>
			<property name="password" value="${db.password}"></property>
		</bean>
		<!-- to configure SqlSessionFactory -->
		<bean class="org.mybatis.spring.SqlSessionFactoryBean">
			<!-- set up MyBatis Core profile -->
			<property name="configLocation" value="classpath:MyBatis/SqlMapConfig.xml"></property>
			<!-- set up data sources -->
			<property name="dataSource" ref="dataSource"></property>
		</bean>
		<!-- to configure Mapper scanning -->
		<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
			<!-- set up Mapper Scan package -->
			<property name="basePackage" value="com.dao"></property>
		</bean>	
</beans>

applicationContext-service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		xmlns="http://www.springframework.org/schema/beans" 
		xmlns:context="http://www.springframework.org/schema/context" 
		xmlns:aop="http://www.springframework.org/schema/aop" 
		xmlns:tx="http://www.springframework.org/schema/tx" 
		xmlns:mvc="http://www.springframework.org/schema/mvc" 
		xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd ">
	
	<!-- to configure Service Layer scanning -->
	<context:component-scan base-package="com.service"></context:component-scan>	
	<!-- Configure transaction management -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- Enable annotation mode management AOP affair -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		xmlns="http://www.springframework.org/schema/beans" 
		xmlns:context="http://www.springframework.org/schema/context" 
		xmlns:aop="http://www.springframework.org/schema/aop" 
		xmlns:tx="http://www.springframework.org/schema/tx" 
		xmlns:mvc="http://www.springframework.org/schema/mvc" 
		xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd ">
		
	<!-- to configure Controller Layer scan package -->	
		<context:component-scan base-package="com.controller"></context:component-scan>
	<!-- Configure annotation driven -->
	<mvc:annotation-driven></mvc:annotation-driven>
	<!-- Configure view parser -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
				<property name="prefix" value="/WEB-INF/jsp"></property>
				<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

dataSource.properties

jdbc.url=jdbc:mysql://localhost:3306/shop_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username=root
jdbc.password=123456
jdbc.driver=com.mysql.jdbc.Driver

WebContent

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>com.ssm.one</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

JSP

index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
    <%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"
		+request.getServerPort()+path;
%>
<html>
<head>
<meta charset="utf-8">
<title>Sign in</title>
</head>
<body>
<script type="text/javascript">
	window.location.href="<%=basePath%>/selectAll.do";
</script>
</body>
</html>

shopOrder.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<head>
<meta charset="utf-8">
<title>Online shopping system</title>

<style type="text/css">
		 h2{
			position:relative;
			left:40%;
		}
		table{
	
			text-align: center;
			
		}
		.foot{
			
			margin-right: 100px;
			float: right;
		}
		tr:hover{
		background: #EEEEEE;
	     }
	   a{
		text-decoration: none;
	   }
	  p{
		text-align: right;
	}
	 </style>
</head>
<body>

<h2>Order management</h2>
 <form action="shooplists.do" method="post">
    <table width="100%" border="1px" cellpadding="3" cellspacing="0">
	 		  <tr style="background-color: #42B983;color:white">
	 		    <th width="80px">Order No</th>
	 		    <th width="150px">Trade name</th>
	 		    <th width="150px">commodity price</th>
	 		    <th width="150px">Purchase quantity</th>
	 		    <th width="150px">Total price of goods</th>
	 		    <th width="200px">Order time </th>
	 		    <th width="150px">Order user</th>
	 		    <th width="150px">Order status</th>
	 		    <th width="200px">operation</th>
	 		  </tr>
	 		  <c:forEach var="list" items="${selectAll }" varStatus="item" >
	 		  	<tr>
	 			    <td width="150px">${list.id}</td>
	 			    <td width="150px">${list.goodname}</td>
	 			    <td width="150px">${list.goodprice}</td>
	 			    <td width="150px">${list.count}</td>
	 			    <td width="150px">${list.total}</td>
	 			    <td width="150px">${list.orderdate}</td>
	 			    <td width="150px">${list.username}</td>
	 			    <td width="150px">
	 			    	<c:if test="${list.state==1}">
	 			    		Order placed
	 			    	</c:if>
	 			    	<c:if test="${list.state==2}">
	 			    		Shipped
	 			    	</c:if>
	 			    	<c:if test="${list.state==3}">
	 			    		Received goods
	 			    	</c:if>
	 			    </td>
	 			    <td width="160px">
	 			    
	 			    <c:if test="${list.state==1}">
	 			        <a href="javascript:if(confirm('Is shipment confirmed for this order?'))location='update1b2.do?id=${list.id}'">deliver goods</a>
	 			         &nbsp; &nbsp; &nbsp; &nbsp;
	 			    	<a href="javascript:if(confirm('Are you sure you want to delete?'))location='del.do?id=${list.id}'">delete</a>
	 			    </c:if>
	 			    <c:if test="${list.state==2}">
	 			    	<a href="javascript:if(confirm('Are you sure to receive the goods?'))location='update2b3.do?id=${list.id}'">Confirm receipt</a>
	 			           &nbsp; &nbsp; &nbsp; &nbsp;
	 			    	 <a href="javascript:if(confirm('Are you sure you want to delete?'))location='del.do?id=${list.id}'">delete</a>
	 			    </c:if>
	 			    <c:if test="${list.state==3}">
	 			    		 <a href="javascript:if(confirm('Are you sure you want to delete?'))location='del.do?id=${list.id}'">delete</a>
	 			    </c:if>
	 			    </td>
	 		 	 </tr>
	 		  </c:forEach>
	 		</table>
</form>
</body>
</html>

Posted by Zpixel on Mon, 22 Nov 2021 20:33:00 -0800