1 introduction

This demo is a small project based on the SSM framework, used for beginners to carry out basic framework proficiency exercises. Obtain the source code at the end of the article, the following is the program to run several pages:

2 Environment Construction

2.1 Basic Architecture

1. Add dependency packages through the Properties Unified Framework version

<properties>
    <springversion>5.0.8. RELEASE</springversion>
</properties>
Copy the code
<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>

  <! Join ServletAPI -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
  </dependency>
  <! MySQL > alter database start -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
  </dependency>
  <! -- Added MyBatis dependency start -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.2.8</version>
  </dependency>
  <! -- Introduce Spring(including SpringMVC) dependency start -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${springversion}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${springversion}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-oxm</artifactId>
    <version>${springversion}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${springversion}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${springversion}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${springversion}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${springversion}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${springversion}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${springversion}</version>
  </dependency>
  <! MyBatis -- Spring is not a new version of MyBatis, but a new version of MyBatis -- Spring is a new version of MyBatis.
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.2</version>
  </dependency>
  <! -- JSTL -->
  <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>
  <! -- Druid data connection pool -->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.9</version>
  </dependency>
  <! -- pagehelper -->
  <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>4.1.6</version>
  </dependency>
  <! - processing json - >
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.5</version>
  </dependency>
  <! --javaee-->
  <dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
  </dependency>
  <! -- File upload and download -->
  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
  </dependency>
  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
  </dependency>
</dependencies>
Copy the code

If you encounter a declarative transaction error, you need to add the following dependency packages

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.1</version>
</dependency>
Copy the code

2. Add the Spring configuration file for eight key steps


      
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <! --1 configure data source -->
    <bean id="db" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/kaikeba0917"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <! - 2 create a sqlSessionFactory -- -- >
    <bean id="fac" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="db"/>
        <! Mybatis configuration file path -->
        <property name="configLocation" value="classpath:mybatis.xml"/>
        <! Mybatis mapper file path -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <! Create sqlSessionTemplate (this class has no no-argument constructor) -->
    <bean class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="fac"/>
    </bean>

    <! --4 config transaction -->
    <bean id="mytx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="db"/>
    </bean>
    <tx:annotation-driven transaction-manager="mytx"/>

    <! -- enable springMVC annotations -->
    <mvc:annotation-driven/>

    <! --6 Configure the view parser -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <! --7 Scan annotation pack -->
    <context:component-scan base-package="com.wangjiawei"/>

    <! Configure static resource access -->
    <mvc:default-servlet-handler/>

</beans>
Copy the code

3. Configure the web. XML file and load the Spring configuration file

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">


  <display-name>Archetype Created Web Application</display-name>

  <! --1 configure front-end controller -->
  <servlet>
    <servlet-name>aa</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring.xml</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>aa</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <! --2 handle post garble -->
  <filter>
    <filter-name>bb</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>bb</filter-name>
    <url-pattern>/ *</url-pattern>
  </filter-mapping>

</web-app>
Copy the code

Dao, service, Web (Controller) package with annotations; dao, web (Controller) package with annotations; dao, Web (Controller) package with attributes:

public interface BooksDao {
    public List<Books> getAll(a);
}
Copy the code
@Repository
public class BookDaoImpl implements BooksDao {

    /** This object is from the configuration file ** /
    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    public List<Books> getAll(a) {
        return sqlSessionTemplate.selectList("com.wangjiawei.dao.BooksDao.getAll"); }}Copy the code

Service:

public interface BooksService {
    public List<Books> getAll(a);
}
Copy the code
@Service
public class BooksServiceImpl implements BooksService {
    @Resource
    private BooksDao dao;

    @Override
    public List<Books> getAll(a) {
        returndao.getAll(); }}Copy the code

Web (Controller) :

@Controller
public class BooksController {
    @Resource
    private BooksService booksService;

    @RequestMapping("/getallbooks")
    public String getAll(ModelMap map){
        List<Books> books = booksService.getAll();
        map.addAttribute("booklist", books);
        return "show"; }}Copy the code

5. Configuration file code mybatis. XML and corresponding booksmapper.xml mybatis


      
<! DOCTYPEconfiguration PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <! -- Alias class -->
    <typeAliases>
<! -- <typeAlias type="com.wangjiawei.bean.Student" alias="stu"></typeAlias>-->
        <package name="com.wangjiawei.bean"/>
    </typeAliases>

    <! -- Paging plugin -->
    <plugins>
        <! - PageHelper4.1.6 -- -- >
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql"/>
        </plugin>
    </plugins>

</configuration>
Copy the code

BooksMapper. XML:


      
<! DOCTYPEmapper PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wangjiawei.dao.BooksDao">
    <select id="getAll" resultType="books">
        select * from books
    </select>
</mapper>
Copy the code

@controller@requestMapping@AutoWired @Qualifier(“empBiz”)

7. Add the following annotations to the service and DAO layer: @service @autoWired (1) The DAO layer omitted the implementation class (2) the DAO layer only defined the interface, from the leaf to create the DAO layer object and scan the mapper file note: when adding the SPRing-JDBC JAR package, the transaction will be automatically committed

8. Front-end test webpage index.jsp:

<html>
<body>
<h2>Hello World!</h2>
<a href="/getallbooks">getallbooks</a>
</body>
</html>
Copy the code

The show. The JSP:

<%@ page contentType="text/html; charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>show.jsp</h1>
    <c:forEach items="${booklist}" var="book">${book. BookId}, ${book. BookName}</c:forEach>
</body>
</html>
Copy the code

When the project starts, the web. XML file loads the spring. XML file, and the Spring configuration file loads the Mybatis configuration file and mapper file.

2.2 Omit the DAO implementation class

Delete the DAO implementation class above

Use MapperScannerConfigurer instead of the SqlSessionTemplate

<! -- Omit implementation class -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.dao"></property>
    <property name="sqlSessionFactoryBeanName" value="fac"></property>
</bean>
Copy the code

Note: You can also test using properties files to load data sources.

2.3 SSM integrates myBatis reverse generation tool

Depend on the package:

<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.5</version>
</dependency>
Copy the code

Loading plug-ins:

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.5</version>
            <configuration>
                <! -- Configuration file path -->
                <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                <overwrite>true</overwrite>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-core</artifactId>
                    <version>1.3.5</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>
Copy the code

Create the Generatorconfig.xml file in the Resource folder according to the contents of the plug-in:


      
<! DOCTYPEgeneratorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<! -- Config generator -->
<generatorConfiguration>
    <! Database driver jar -->
    <classPathEntry
            location=F: \ "develop \ maven_repository/mysql/mysql - connector - Java \ 5.1.6 \ mysql connector - Java - 5.1.6. Jar" />
    <context id="MyBatis" targetRuntime="MyBatis3">
        <! -- Remove comments -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <! -- Database connection -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/kaikeba0917"
                        userId="root"
                        password="root">
        </jdbcConnection>
        <! Maven-generated entity class specifies the package name and the generated address (you can customize the address, but the path does not exist) -->
        <javaModelGenerator targetPackage="com.wangjiawei.bean"
                            targetProject="D:\ programmer \ Start new career \11SSM\5SSM integration \ SSM\ SRC \main\ Java">
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <! Create SQLmapper file -->
        <sqlMapGenerator targetPackage="mapper"
                         targetProject="D:\ programmer \ Start new career \11SSM\5SSM integration \ SSM\ SRC \main\resources">
        </sqlMapGenerator>
        <! Create Dao file, create interface -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.wangjiawei.dao"
                             targetProject="D:\ programmer \ Start new career \11SSM\5SSM integration \ SSM\ SRC \main\ Java">
        </javaClientGenerator>
        <table tableName="student" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>
Copy the code

Load mybatis- Generator plugin for Maven-type Web projects:

Note: after the reverse generation, it is best to delete this command, otherwise accidentally after the point, will generate again code, especially mapper. XML file SQL statement will generate again, runtime error.

3 Accounting Items

3.1 Requirement Analysis

3.1.1 Accounting management

The type of query conditions is a drop-down list, and the optional values are “unlimited, expenditure, income, transfer, lend, borrow, return in, return out”. Enter the date string in YYYY-MM-DD format in the date input box. Click The Search button to submit the form. If the input items do not meet the requirements, the corresponding prompt information will be displayed. In the list, the corresponding “+, -” symbol is added before the amount according to the accounting category. If the category is “expenditure, debit, return”, the “-” symbol is added before the amount. If the category is “revenue, borrowed, returned”, add “+” before the amount. If no bill data is found after querying according to the input items, a prompt message will be given, as shown in the figure:

Click “bookkeeping” button, enter the bookkeeping page.

3.1.2 charge to an account

  • The maximum length of the title input box is 25 characters. The value of the date input box must be in yyyY-MM-DD format. The value of the amount input box must be a number greater than 0.
  • Click “Reset” button to restore the initial value
  • Click “Save” button to perform the save function. You must use JS validation before submitting data to the Controller. If the input values of each attribute do not meet the requirements, prompt the user.
  • Click the “Back” button to abandon the current billing operation. And return to the home page.

Function supplement: Add a column after the “description” column, called “operation”. Users can delete or modify data. Paging display: Previous page Next page Last page Current page Total number of pages Total number of pages

3.1.3 Reference Database

create table bills(
	id int primary key auto_increment,
	title varchar(50),
	billtime date,
	typeid int,
	price double,
	explains varchar(50));create table billtype(
	id int primary key auto_increment,
	bname varchar(5));Copy the code

3.2 Environment Construction

Start by creating a basic directory

XML, spring. XML, Mybatis. XML, GeneratorConfig. XML, and then generate them automatically using mybatis automatic generation function

3.3 Querying Data

Configure the request dispatcher in web.xml and handle POST garbled characters

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>Archetype Created Web Application</display-name>

  <! --1 configure front-end controller -->
  <servlet>
    <servlet-name>aa</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring.xml</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>aa</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <! --2 handle post garble -->
  <filter>
    <filter-name>bb</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>bb</filter-name>
    <url-pattern>/ *</url-pattern>
  </filter-mapping>


</web-app>
Copy the code

3.3.1 Displaying the drop-down list and basic information

The dao: BillsMapper

package com.wangjiawei.dao;

import com.wangjiawei.bean.Bills;

import java.util.List;

public interface BillsMapper {

    /** * query all bills *@return* /
    public List<Bills> getBills(a);

    int deleteByPrimaryKey(Integer id);

    int insert(Bills record);

    int insertSelective(Bills record);

    Bills selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Bills record);

    int updateByPrimaryKey(Bills record);
}
Copy the code

Add the corresponding implementation to billSmapper.xml:

<resultMap id="BaseResultMap" type="com.wangjiawei.bean.Bills">
  <id column="id" jdbcType="INTEGER" property="id" />
  <result column="title" jdbcType="VARCHAR" property="title" />
  <result column="billtime" jdbcType="DATE" property="billtime" />
  <result column="typeid" jdbcType="INTEGER" property="typeid" />
  <result column="price" jdbcType="DOUBLE" property="price" />
  <result column="explains" jdbcType="VARCHAR" property="explains" />
</resultMap>

<select id="getBills" resultMap="BaseResultMap">
  select * from bills
</select>
Copy the code

BillTypeMapper

package com.wangjiawei.dao;

import com.wangjiawei.bean.Billtype;

import java.util.List;

public interface BilltypeMapper {

    /** * Query all bill types *@return* /
    public List<Billtype> getTypes(a);

    int deleteByPrimaryKey(Integer id);

    int insert(Billtype record);

    int insertSelective(Billtype record);

    Billtype selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Billtype record);

    int updateByPrimaryKey(Billtype record);
}
Copy the code

Add the corresponding implementation to billtypemapper.xml:

<resultMap id="BaseResultMap" type="com.wangjiawei.bean.Billtype">
  <id column="id" jdbcType="INTEGER" property="id" />
  <result column="bname" jdbcType="VARCHAR" property="bname" />
</resultMap>

<select id="getTypes" resultMap="BaseResultMap">
  select * from billtype
</select>
Copy the code

BillsService interface:

public interface BillsService {

    /** * query all bills *@return* /
    public List<Bills> getBills(a);
}
Copy the code

BillsServiceImpl implementation class:

@Service
public class BillsServiceImpl implements BillsService {

    @Resource
    private BillsMapper billsMapper;

    /** * query all bills **@return* /
    @Override
    public List<Bills> getBills(a) {
        returnbillsMapper.getBills(); }}Copy the code

BillTypesService interface:

public interface BillTypesService {

    /** * Query all bill types *@return* /
    public List<Billtype> getTypes(a);
}
Copy the code

BillTypesService implementation class:

@Service
public class BillTypesServiceImpl implements BillTypesService {
    @Resource
    private BilltypeMapper billtypeMapper;

    /** * Query all bill types **@return* /
    @Override
    public List<Billtype> getTypes(a) {
        returnbilltypeMapper.getTypes(); }}Copy the code

The controller layer: BillsController

@Controller
public class BillsController {
    @Resource
    private BillTypesService typesService;
    @Resource
    private BillsService billsService;

    @RequestMapping("/gettypes")
    public String gettypes(ModelMap map){
        // 1 Query all bill types
        List<Billtype> types = typesService.getTypes();
        // 2 Query all bills
        List<Bills> bills = billsService.getBills();
        // Save the data to the foreground
        map.addAttribute("types", types);
        map.addAttribute("bills", bills);
        return "show"; }}Copy the code

The corresponding front-end interface: index.jsp

<html>
<body>
<script type="application/javascript">
    location.href = "/gettypes";
</script>
</body>
</html>
Copy the code

show.jsp

<%-- Created by IntelliJ IDEA. User: 12291 Date: 2020/10/30 Time: 10:26 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html; charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>Management of charge to an account</h1>

<p>
    <form>Type:<select>
        <option value="1">There is no limit</option>
        <c:forEach items="${types}" var="tp">
            <option value="${tp.id}">${tp.bname}</option>
        </c:forEach>
    </select>Time:<input type="text" name="begin">to<input type="text" name="end">
        <input type="submit" value="Search">
    </form>
        <input type="button" value="Accounting">
</p>
<table border="1" width="500">
    <tr>
        <td>The title</td>
        <td>Time of charge to an account</td>
        <td>category</td>
        <td>The amount of</td>
        <td>instructions</td>
        <td>operation</td>
    </tr>

    <c:forEach items="${bills}" var="bill">
        <tr>
            <td>${bill.title}</td>
            <td><fmt:formatDate value="${bill.billtime}" pattern="yyyy-MM-dd"/></td>
            <td>category</td>
            <td>${bill.price}</td>
            <td>${bill.explains}</td>
            <td>Delete modify</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>
Copy the code

3.3.2 Display of [Category] part of front-end page

Two tables are needed for joint checking:

select * from bills b, billtype t where b.typeid = t.id;
Copy the code

Add a one-to-many relationship for the entity class first:Add attributes to the Bills class

private Billtype billtype;
Copy the code

Add attributes to BillType

private List<Bills> billsList;
Copy the code

Mapper. XML: billsmapper. XML (this is the only one you need to change to show the category)

<resultMap id="rs1" type="bills">
  <id column="id" jdbcType="INTEGER" property="id" />
  <result column="title" jdbcType="VARCHAR" property="title" />
  <result column="billtime" jdbcType="DATE" property="billtime" />
  <result column="typeid" jdbcType="INTEGER" property="typeid" />
  <result column="price" jdbcType="DOUBLE" property="price" />
  <result column="explains" jdbcType="VARCHAR" property="explains" />

  <association property="billtype" javaType="com.wangjiawei.bean.Billtype">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="bname" jdbcType="VARCHAR" property="bname" />
  </association>
</resultMap>

<select id="getBills" resultMap="rs1">
  select * from bills b, billtype t where b.typeid = t.id;
</select>
Copy the code

Modify front-end show.jsp:

3.3.3 Display of [Amount] in front page

Expenditure, you should have a minus sign when you lend the amount and you just use choose when in the front interface

<c:forEach items="${bills}" var="bill">
    <tr>
        <td>${bill.title}</td>
        <td><fmt:formatDate value="${bill.billtime}" pattern="yyyy-MM-dd"/></td>
        <td>${bill.billtype.bname}</td>
        <td>
            <c:choose>
                <c:when test="${bill. Billtype. Bname = = 'spending' | | bill. Billtype. Bname = = 'lend' | | bill. Billtype. Bname = = 'is a'}">
                    -${bill.price}
                </c:when>
                <c:when test="${bill. Billtype. Bname = = 'income' | | bill. Billtype. Bname = = 'borrowing' | | bill. Billtype. Bname = = 'also into the'}">
                    +${bill.price}
                </c:when>
                <c:otherwise>
                    ${bill.price}
                </c:otherwise>
            </c:choose>
        </td>
        <td>${bill.explains}</td>
        <td>Delete modify</td>
    </tr>
</c:forEach>
Copy the code

3.3.4 Fuzzy Query By Time and Type

In fact, the query all statement and the fuzzy query statement is the same statement, but the fuzzy query statement is based on the query all statement concatenation, the two queries can call the same interface.

Front page: Add a form for the search section

<form action="/getAllBills" method="post">Type:<select name="typeid">
    <option value="1">There is no limit</option>
    <c:forEach items="${types}" var="tp">
        <option value="${tp.id}"The ${tid= =tp.id?'selected':"'} >${tp.bname}</option>
    </c:forEach>
</select>Time:<input type="text" name="begin" value="${begintime}">to<input type="text" name="end" value="${endtime}">
    <input type="submit" value="Search">
</form>
    <input type="button" value="Accounting">
Copy the code

Controller layer: Add getAllBills to query all methods. Echo operation is added, because the echo operation is also displayed according to the ID of the type (see the front interface), so we also need to query all types here.

/** * query all bills *@return* /
@RequestMapping("/getAllBills")
public String getBills(Integer typeid, String begin, String end, ModelMap map){

    List<Bills> bills = billsService.getBills(typeid, begin, end);
    map.addAttribute("bills", bills);
    // Data is displayed
    // Return the conditional value of the fuzzy query to the foreground
    map.addAttribute("tid", typeid);
    map.addAttribute("begintime", begin);
    map.addAttribute("endtime", end);

    List<Billtype> types = typesService.getTypes();
    map.addAttribute("types", types);

    return "show";
}
Copy the code

Service layer: DAO interface:

public List<Bills> getBills(int typeid, String begin, String end);
Copy the code

Dao implementation classes:

/** * query all bills **@return* /
@Override
public List<Bills> getBills(int typeid, String begin, String end) {
    Map params = new HashMap();
    params.put("tid", typeid);
    params.put("begin", begin);
    params.put("end", end);
    return billsMapper.getBills(params);
}
Copy the code

Dao: Modify the getBills method of BillsMapper

public List<Bills> getBills(Map map);
Copy the code

The corresponding configuration file is billsmapper.xml

<resultMap id="rs1" type="bills">
  <id column="id" jdbcType="INTEGER" property="id" />
  <result column="title" jdbcType="VARCHAR" property="title" />
  <result column="billtime" jdbcType="DATE" property="billtime" />
  <result column="typeid" jdbcType="INTEGER" property="typeid" />
  <result column="price" jdbcType="DOUBLE" property="price" />
  <result column="explains" jdbcType="VARCHAR" property="explains" />

  <association property="billtype" javaType="com.wangjiawei.bean.Billtype">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="bname" jdbcType="VARCHAR" property="bname" />
  </association>
</resultMap>

<select id="getBills" resultMap="rs1">
  select * from bills b, billtype t where b.typeid = t.id
  <if test="tid != -1">
    and t.id=#{tid}
  </if>
  <if test="begin! =null and begin! = "">
    and b.billtime>=#{begin}
  </if>
  <if test="end! =null and end! = "">and b.billtime <! [CDATA[ <= ]]> #{end}</if>
</select>
Copy the code

3.3.5 Paging display

Use the utility class PageHelper for paging, which is done at the Service layer.

Service: new parameters need to be received for paging query. Current page number: index and number of pages displayed per page size interface

public PageInfo<Bills> getBills(int typeid, String begin, String end, int index, int size);
Copy the code

Implementation class:

@Service
public class BillsServiceImpl implements BillsService {

    @Resource
    private BillsMapper billsMapper;

    /** * query all bills **@return* /
    @Override
    public PageInfo<Bills> getBills(int typeid, String begin, String end, int index, int size) {
        Map params = new HashMap();
        params.put("tid", typeid);
        params.put("begin", begin);
        params.put("end", end);

        // 1 Specifies paging data
        PageHelper.startPage(index, size);
        // 2 Query data
        List<Bills> bills = billsMapper.getBills(params);
        // 3 Create the paging utility class
        PageInfo<Bills> info = new PageInfo<>(bills);

        returninfo; }}Copy the code

Controller layer: the controller changes the query operation call, passing in a size and index, and the data returned to the front end becomes a PageInfo object

@RequestMapping("/gettypes")
public String gettypes(ModelMap map){
    // 1 Query all bill types
    List<Billtype> types = typesService.getTypes();

    // 2 Query all bills
    PageInfo<Bills> info = billsService.getBills(-1.null.null.1, PageUtil.PAGESIZE);

    // Save the data to the foreground
    map.addAttribute("types", types);
    map.addAttribute("info", info);

    return "show";
}
Copy the code
@RequestMapping("/getAllBills")
public String getBills(@RequestParam(defaultValue = "1") int index, @RequestParam(defaultValue = "-1") Integer typeid, String begin, String end, ModelMap map){

    PageInfo<Bills> info = billsService.getBills(typeid, begin, end, index, PageUtil.PAGESIZE);
    map.addAttribute("info", info);
    // Data is displayed
    // Return the conditional value of the fuzzy query to the foreground
    map.addAttribute("tid", typeid);
    map.addAttribute("begintime", begin);
    map.addAttribute("endtime", end);

    List<Billtype> types = typesService.getTypes();
    map.addAttribute("types", types);

    return "show";
}
Copy the code

Index is defined as a constant 3

public interface PageUtil {
    public int PAGESIZE = 3;
}
Copy the code

Front-end page: the data returned to the front-end background into PageInfo objects; To control click on the previous page, the next page display range; Remember to include fuzzy query parameters when paging queries;

<%-- Created by IntelliJ IDEA. User: 12291 Date: 2020/10/30 Time: 10:26 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html; charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>Management of charge to an account</h1>

<p>
    <form action="/getAllBills" method="post">Type:<select name="typeid">
        <option value="1">There is no limit</option>
        <c:forEach items="${types}" var="tp">
            <option value="${tp.id}"The ${tid= =tp.id?'selected':"'} >${tp.bname}</option>
        </c:forEach>
    </select>Time:<input type="text" name="begin" value="${begintime}">to<input type="text" name="end" value="${endtime}">
        <input type="submit" value="Search">
    </form>
        <input type="button" value="Accounting">
</p>

<table border="1" width="500">
    <tr>
        <td>The title</td>
        <td>Time of charge to an account</td>
        <td>category</td>
        <td>The amount of</td>
        <td>instructions</td>
        <td>operation</td>
    </tr>

    <c:if test="${info.list.size() > 0}">
        <c:forEach items="${info.list}" var="bill">
            <tr>
                <td>${bill.title}</td>
                <td><fmt:formatDate value="${bill.billtime}" pattern="yyyy-MM-dd"/></td>
                <td>${bill.billtype.bname}</td>
                <td>
                    <c:choose>
                        <c:when test="${bill. Billtype. Bname = = 'spending' | | bill. Billtype. Bname = = 'lend' | | bill. Billtype. Bname = = 'is a'}">
                            -${bill.price}
                        </c:when>
                        <c:when test="${bill. Billtype. Bname = = 'income' | | bill. Billtype. Bname = = 'borrowing' | | bill. Billtype. Bname = = 'also into the'}">
                            +${bill.price}
                        </c:when>
                        <c:otherwise>
                            ${bill.price}
                        </c:otherwise>
                    </c:choose>
                </td>
                <td>${bill.explains}</td>
                <td>Delete modify</td>
            </tr>
        </c:forEach>
    </c:if>

    <c:if test="${info.list.size() == 0}">
        <tr>
            <td colspan="6"> <h3>No data was found</h3> </td>
        </tr>
    </c:if>

    <tr>
        <td colspan="6">
            <a href="/getAllBills? typeid=${tid}&begin=${begintime}&end=${endtime}">Home page</a>

            <a href="/getAllBills? index=${info.prePage==0? 1:info.prePage}&typeid=${tid}&begin=${begintime}&end=${endtime}">The previous page</a>

            <a href="/getAllBills? index=${info.nextPage==0? info.pages:info.nextPage}&typeid=${tid}&begin=${begintime}&end=${endtime}">The next page</a>

            <a href="/getAllBills? index=${info.pages}&typeid=${tid}&begin=${begintime}&end=${endtime}">back</a>${info.pages} ${info.total}</td>
    </tr>

</table>
</body>
</html>
Copy the code

3.4 Billing Function (New data)

Front page: Note that the name in the page must be the same as the property name of the Bill class behind the page

<%-- Created by IntelliJ IDEA. User: 12291 Date: 2020/10/30 Time: 16:52 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html; charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>Charge to an account</h1>
    <form action="/insertBill" method="post">
<p>Type:<c:forEach items="${types}" var="ty">
        <input type="radio" value="${ty.id}" name="typeid">${ty.bname}
    </c:forEach>
</p>
<p>Title:<input type="text" style="width: 500px" name="title"></p>
<p>Date:<input type="text" name="billtime">Amount:<input type="text" name="price"></p>
<p>Description:<textarea cols="50" rows="4" name="explains"></textarea></p>
        <input type="reset" value="Reset">
        <input type="submit" value="Save">
    </form>
</body>
</html>
Copy the code

The dao layer code is automatically generated, so you already have the insert method, which starts directly from the service layer:

public int insert(Bills record);
Copy the code

Implementation class, note to enable transactions:

@Override
@Transactional
public int insert(Bills record) {
    return billsMapper.insert(record);
}
Copy the code

Controller:

@RequestMapping("/insertBill")
public String add(Bills bills){
    int insert = billsService.insert(bills);
    if (insert > 0) {// Return to the main page
        return "redirect:/gettypes";
    }
    // Return to the new page
    return "redirect:/getBillType";
}
Copy the code

Note when testing that the default springMVC date input format is 2020/2/2 split with a slash.

3.5 Updating bills

Update bill actually divided into two operations, one is to query the bill, one is to modify the bill

3.5.1 Querying Bills

Add an A tag for the modification action in show.jsp

<a href="/findById? bid=${bill.id}">Modify the</a>
Copy the code

Controller defines the corresponding method:

@RequestMapping("/findById")
public String findById(int bid, ModelMap map){
    Bills bills = billsService.selectByPrimaryKey(bid);
    List<Billtype> types = typesService.getTypes();
    map.addAttribute("bills", bills);
    map.addAttribute("types", types);
    return "update";
}
Copy the code

Service layer:

Bills selectByPrimaryKey(Integer id);
Copy the code

Implementation class:

@Override
public Bills selectByPrimaryKey(Integer id) {
    return billsMapper.selectByPrimaryKey(id);
}
Copy the code

Daos are automatically generated:

<sql id="Base_Column_List">
  id, title, billtime, typeid, price, explains
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
  select 
  <include refid="Base_Column_List" />
  from bills
  where id = #{id,jdbcType=INTEGER}
</select>
Copy the code

Front-end interface: The Controller returns an update.jsp page

<%@ page contentType="text/html; charset=UTF-8" language="java" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>update</h1>
    <form action="/updateBill" method="post">
        <input type="hidden" name="id" value="${bills.id}">
        <p>Type:<c:forEach items="${types}" var="ty">
                <input type="radio" value="${ty.id}"The ${ty.id= =bills.typeid?"checked":""} name="typeid">${ty.bname}
            </c:forEach>
        </p>
        <p>Title:<input type="text" style="width: 500px" name="title" value="${bills.title}"></p>
        <p>Date:<input type="text" name="billtime" value="<fmt:formatDate value="The ${bills.billtime}" pattern="yyyy/MM/dd"/>"> amount:<input type="text" name="price" value="${bills.price}"></p>
        <p>Description:<textarea cols="50" rows="4" name="explains">${bills.explains}</textarea></p>
        <input type="reset" value="Reset">
        <input type="submit" value="Save">
    </form>
</body>
</html>
Copy the code

3.5.2 Modifying operations

Controller:

@RequestMapping("/updateBill")
public String updateBill(Bills bills){
    int i = billsService.updateByPrimaryKey(bills);
    if (i > 0) {return "redirect:/gettypes";
    }
    return "redirect:/findById? bid=" + bills.getId();
}
Copy the code

If the modification succeeds, the show page is displayed. If the modification fails, the Update page is displayed.

Service layer:

@Override
public int updateByPrimaryKey(Bills record) {
    return billsMapper.updateByPrimaryKey(record);
}
Copy the code

Daos are also automatically generated:

<update id="updateByPrimaryKey" parameterType="com.wangjiawei.bean.Bills">
  update bills
  set title = #{title,jdbcType=VARCHAR},
    billtime = #{billtime,jdbcType=DATE},
    typeid = #{typeid,jdbcType=INTEGER},
    price = #{price,jdbcType=DOUBLE},
    explains = #{explains,jdbcType=VARCHAR}
  where id = #{id,jdbcType=INTEGER}
</update>
Copy the code

3.5.3 Deleting a vm

Add a button for delete in show.jsp

<a href="/deleteById? bid=${bill.id}">delete</a>
Copy the code

Controller layer: Add and delete methods

@RequestMapping("/deleteById")
public void delete(int bid, HttpServletResponse response){
    int i = billsService.deleteByPrimaryKey(bid);
    response.setContentType("text/html; charset=utf-8");
    try {
        PrintWriter writer  = response.getWriter();
        if (i > 0){
            writer.print("");
            return;
        }
        writer.print("");
    } catch(IOException e) { e.printStackTrace(); }}Copy the code

Service layer: interfaces

public int deleteByPrimaryKey(Integer id);
Copy the code

The implementation class

@Override
@Transactional
public int deleteByPrimaryKey(Integer id) {
    return billsMapper.deleteByPrimaryKey(id);
}
Copy the code

About source code:You can download through my main download business, or there is my personal contact information in the public number