欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD

程序员文章站 2022-12-05 14:26:24
在学习spring4+springmvc+mybatis的ssm框架,idea整合简单实现增删改查功能,在这里记录一下。 "原文在这里:https://my.oschina.net/finchxu/blog/3007984" 工作环境: Windows 10 jdk8(1.8) IntelliJ I ......

在学习spring4+springmvc+mybatis的ssm框架,idea整合简单实现增删改查功能,在这里记录一下。


工作环境:

  • windows 10
  • jdk8(1.8)
  • intellij idea 
  • spring 4 和 springmvc
  • mysql 5.7
  • maven 3.3
  • mybatis 3.4
  • dbcp
  • tomcat 8.5

项目上传到了github方便查看: 有用的话欢迎加星。

页面演示:

idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD

首先新建项目

如图所示新建maven的webapp

idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD

建数据库和数据表

create database books;
create table `bookadmin`  (
  `bid` int(11) not null auto_increment,
  `bn` varchar(255) character set utf8 collate utf8_general_ci not null,
  `author` varchar(255) character set utf8 collate utf8_general_ci not null,
  `press` varchar(255) character set utf8 collate utf8_general_ci not null,
  primary key (`bid`) using btree
) engine = innodb auto_increment = 14 character set = utf8 collate = utf8_general_ci row_format = dynamic;

idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD

这里是项目目录结构

springbook
   ├── src
   │   └── main
   │       ├── java
   │       │   └── cn
   │       │       └── book
   │       │           ├── controller
   │       │           │   └── bookscontroller.java
   │       │           ├── mapper
   │       │           │   ├── booksmapper.java
   │       │           │   └── booksmapper.xml
   │       │           ├── pojo
   │       │           │   └── bookadmin.java
   │       │           └── service
   │       │               ├── booksserviceimpl.java
   │       │               └── booksservice.java
   │       ├── resources
   │       │   ├── applicationcontext-dao.xml
   │       │   ├── applicationcontext-service.xml
   │       │   ├── applicationcontext-trans.xml
   │       │   ├── jdbc.properties
   │       │   ├── log4j.properties
   │       │   ├── spring-mvc.xml
   │       │   └── sqlmapconfig.xml
   │       └── webapp
   │           ├── index.jsp
   │           └── web-inf
   │               ├── jsp
   │               │   ├── listbooks.jsp
   │               │   ├── savepage.jsp
   │               │   └── updatepage.jsp
   │               └── web.xml

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>cn.book</groupid>
  <artifactid>spring</artifactid>
  <version>1.0-snapshot</version>
  <packaging>war</packaging>
  <name>spring maven webapp</name>
  <!-- fixme change it to the project's website -->
  <url>http://www.example.com</url>
  <properties>
    <project.build.sourceencoding>utf-8</project.build.sourceencoding>
    <project.reporting.outputencoding>utf-8</project.reporting.outputencoding>
    <!--<maven.compiler.source>1.8</maven.compiler.source>-->
    <!--<maven.compiler.target>1.8</maven.compiler.target>-->
    <spring.version>4.3.19.release</spring.version>
    <validator.version>5.2.4.final</validator.version>
    <slf4j.version>1.7.7</slf4j.version>
    <commons-lang3.version>3.3.2</commons-lang3.version>
    <commons-io.version>2.4</commons-io.version>
    <commons-codec.version>1.9</commons-codec.version>
    <commons-fileupload.version>1.3.1</commons-fileupload.version>
    <commons-beanutils.version>1.9.1</commons-beanutils.version>
  </properties>
  <dependencies>
    <!-- web begin -->
      <dependency>
          <groupid>org.mybatis</groupid>
          <artifactid>mybatis</artifactid>
          <version>3.2.8</version>
      </dependency>
      <dependency>
          <groupid>org.mybatis</groupid>
          <artifactid>mybatis-spring</artifactid>
          <version>1.2.2</version>
      </dependency>
      <dependency>
          <groupid>mysql</groupid>
          <artifactid>mysql-connector-java</artifactid>
          <version>5.1.29</version>
      </dependency>
      <dependency>
      <groupid>org.apache.maven.plugins</groupid>
      <artifactid>maven-compiler-plugin</artifactid>
      <version>2.3.2</version>
    </dependency>
    <dependency>
      <groupid>taglibs</groupid>
      <artifactid>standard</artifactid>
      <version>1.1.2</version>
      <type>jar</type>
    </dependency>
    <dependency>
      <groupid>javax.servlet</groupid>
      <artifactid>jstl</artifactid>
      <version>1.2</version>
      <type>jar</type>
    </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.1</version>
      <!--<scope>provided</scope>-->
    </dependency>
    <!-- web end -->
    <!-- spring begin -->
    <dependency>
      <groupid>commons-dbcp</groupid>
      <artifactid>commons-dbcp</artifactid>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupid>com.esotericsoftware.reflectasm</groupid>
      <artifactid>reflectasm</artifactid>
      <version>1.09</version>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-web</artifactid>
      <version>4.2.6.release</version>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-webmvc</artifactid>
      <version>4.2.6.release</version>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-core</artifactid>
      <version>${spring.version}</version>
      <exclusions>
        <exclusion>
          <groupid>commons-logging</groupid>
          <artifactid>commons-logging</artifactid>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-beans</artifactid>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-context</artifactid>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-context-support</artifactid>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-aop</artifactid>
      <version>${spring.version}</version>
      <exclusions>
        <exclusion>
          <groupid>commons-logging</groupid>
          <artifactid>commons-logging</artifactid>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-tx</artifactid>
      <version>${spring.version}</version>
    </dependency>
    <!-- spring orm -->
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-orm</artifactid>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-jdbc</artifactid>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupid>javax.inject</groupid>
      <artifactid>javax.inject</artifactid>
      <version>1</version>
    </dependency>
    <!-- bean validate -->
    <!--<dependency>-->
      <!--<groupid>org.hibernate</groupid>-->
      <!--<artifactid>hibernate-validator</artifactid>-->
      <!--<version>${validator.version}</version>-->
    <!--</dependency>-->
    <!-- spring end -->
    <!-- aop begin -->
    <dependency>
      <groupid>org.aspectj</groupid>
      <artifactid>aspectjrt</artifactid>
      <version>1.7.4</version>
    </dependency>
    <dependency>
      <groupid>org.aspectj</groupid>
      <artifactid>aspectjweaver</artifactid>
      <version>1.7.4</version>
    </dependency>
    <dependency>
      <groupid>cglib</groupid>
      <artifactid>cglib</artifactid>
      <version>3.1</version>
    </dependency>
    <!-- aop end -->
    <!-- test begin -->
    <dependency>
      <groupid>junit</groupid>
      <artifactid>junit</artifactid>
      <version>4.12</version>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-test</artifactid>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-oxm</artifactid>
      <version>${spring.version}</version>
    </dependency>
    <!-- test end -->
    <!-- logging begin -->
    <dependency>
      <groupid>org.slf4j</groupid>
      <artifactid>slf4j-api</artifactid>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupid>org.slf4j</groupid>
      <artifactid>slf4j-log4j12</artifactid>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- common-logging 实际调用slf4j -->
    <dependency>
      <groupid>org.slf4j</groupid>
      <artifactid>jcl-over-slf4j</artifactid>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- java.util.logging 实际调用slf4j -->
    <dependency>
      <groupid>org.slf4j</groupid>
      <artifactid>jul-to-slf4j</artifactid>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- logging end -->
    <dependency>
      <groupid>commons-lang</groupid>
      <artifactid>commons-lang</artifactid>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupid>commons-io</groupid>
      <artifactid>commons-io</artifactid>
      <version>${commons-io.version}</version>
    </dependency>
    <dependency>
      <groupid>commons-codec</groupid>
      <artifactid>commons-codec</artifactid>
      <version>${commons-codec.version}</version>
    </dependency>
    <dependency>
      <groupid>commons-fileupload</groupid>
      <artifactid>commons-fileupload</artifactid>
      <version>${commons-fileupload.version}</version>
    </dependency>
    <dependency>
      <groupid>commons-beanutils</groupid>
      <artifactid>commons-beanutils</artifactid>
      <version>${commons-beanutils.version}</version>
      <exclusions>
        <exclusion>
          <groupid>commons-logging</groupid>
          <artifactid>commons-logging</artifactid>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupid>org.projectlombok</groupid>
      <artifactid>lombok</artifactid>
      <version>1.16.18</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <defaultgoal>install</defaultgoal>
    <pluginmanagement>
      <plugins>
        <plugin>
          <groupid>org.apache.maven.plugins</groupid>
          <artifactid>maven-compiler-plugin</artifactid>
          <version>2.3.2</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <maxmem>256m</maxmem>
          </configuration>
        </plugin>
        <plugin>
          <groupid>org.apache.maven.plugins</groupid>
          <artifactid>maven-idea-plugin</artifactid>
          <version>2.2</version>
          <configuration>
            <downloadsources>true</downloadsources>
            <downloadjavadocs>true</downloadjavadocs>
          </configuration>
        </plugin>
        <plugin>
          <groupid>org.apache.maven.plugins</groupid>
          <artifactid>maven-resources-plugin</artifactid>
          <version>2.4.3</version>
        </plugin>
        <plugin>
          <groupid>org.apache.maven.plugins</groupid>
          <artifactid>maven-clean-plugin</artifactid>
          <version>2.4.1</version>
          <configuration>
            <filesets>
              <fileset>
                <directory>activemq-data</directory>
              </fileset>
            </filesets>
          </configuration>
        </plugin>
        <plugin>
          <groupid>org.apache.maven.plugins</groupid>
          <artifactid>maven-install-plugin</artifactid>
          <version>2.3.1</version>
        </plugin>
        <plugin>
          <artifactid>maven-remote-resources-plugin</artifactid>
          <version>1.1</version>
        </plugin>
        <plugin>
          <groupid>org.apache.maven.plugins</groupid>
          <artifactid>maven-jar-plugin</artifactid>
          <version>2.2</version>
        </plugin>
        <plugin>
          <groupid>org.apache.maven.plugins</groupid>
          <artifactid>maven-dependency-plugin</artifactid>
          <version>2.1</version>
        </plugin>
        <plugin>
          <groupid>org.apache.maven.plugins</groupid>
          <artifactid>maven-surefire-plugin</artifactid>
          <version>2.5</version>
        </plugin>
        <plugin>
          <groupid>org.apache.maven.plugins</groupid>
          <artifactid>maven-checkstyle-plugin</artifactid>
          <version>2.6</version>
        </plugin>
        <plugin>
          <groupid>org.codehaus.mojo</groupid>
          <artifactid>exec-maven-plugin</artifactid>
          <version>1.1.1</version>
        </plugin>
      </plugins>
    </pluginmanagement>
    <plugins>
      <plugin>
        <groupid>org.apache.maven.plugins</groupid>
        <artifactid>maven-surefire-plugin</artifactid>
        <configuration>
          <childdelegation>false</childdelegation>
          <usefile>true</usefile>
          <failifnotests>false</failifnotests>
          <includes>
            <include>**/*test.java</include>
          </includes>
        </configuration>
      </plugin>
    </plugins>
     <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
       <resource>
       <directory>src/main/resources</directory>
       <includes>
         <include>**/*.properties</include>
         <include>**/*.xml</include>
       </includes>
       <filtering>false</filtering>
       </resource>
    </resources>
  </build>
</project>
一定要注意这段内容,在maven打包war时扫描这些xml文件     
<resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
       <resource>
       <directory>src/main/resources</directory>
       <includes>
         <include>**/*.properties</include>
         <include>**/*.xml</include>
       </includes>
       <filtering>false</filtering>
       </resource>
</resources>

resources

applicationcontext-dao.xml 用的dbcp连接池。

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
    xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    <!-- 数据库连接池 -->
    <bean id="propertyconfigurer" class="org.springframework.beans.factory.config.propertyplaceholderconfigurer">
        <property name="location" value="classpath:jdbc.properties"/>
    </bean>
    <bean id="datasource" class="org.apache.commons.dbcp.basicdatasource" destroy-method="close">
        <property name="driverclassname" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 连接池的最大数据库连接数 -->
        <property name="maxactive" value="${jdbc.maxactive}" />
        <!-- 最大空闲数 -->
        <property name="maxidle" value="${jdbc.maxidle}" />
    </bean>
    <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean">
        <property name="datasource" ref="datasource" />
        <!-- 加载mybatis核心配置文件 -->
        <property name="configlocation" value="classpath:sqlmapconfig.xml" />
        <!-- 别名包扫描 -->
        <property name="typealiasespackage" value="cn.book.pojo" />
    </bean>
    <!-- 动态代理,第二种方式:包扫描(推荐): -->
    <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer">
        <!-- basepackage多个包用","分隔 -->
        <property name="basepackage" value="cn.book.mapper" />
    </bean>
</beans>

applicationcontext-service.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
    xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    <!-- @service包扫描器 -->
    <context:component-scan base-package="cn.book.service"/>
</beans>

applicationcontext-trans.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
    xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    <!-- 事务管理器 -->
    <bean id="transactionmanager"
        class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
        <!-- 数据源 -->
        <property name="datasource" ref="datasource" />
    </bean>
    <!-- 通知 -->
    <tx:advice id="txadvice" transaction-manager="transactionmanager">
        <tx:attributes>
            <!-- 传播行为 -->
            <tx:method name="save*" propagation="required" />
            <tx:method name="insert*" propagation="required" />
            <tx:method name="delete*" propagation="required" />
            <tx:method name="update*" propagation="required" />
            <tx:method name="find*" propagation="supports" read-only="true" />
            <tx:method name="get*" propagation="supports" read-only="true" />
            <tx:method name="query*" propagation="supports" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <!--&lt;!&ndash; 切面 &ndash;&gt;-->
    <!--<aop:config>-->
        <!--<aop:advisor advice-ref="txadvice"-->
            <!--pointcut="execution(* cn.book.service.*.*(..))" />-->
    <!--</aop:config>-->
</beans>

jdbc.properties 这里要注意应定要加上“jdbc.”的前缀。我用的是mysql5.7所以driver直接这么写就行,如果是mysql6及以上的就不一样了,具体百度吧。

如果遇到什么时区问题,记得在url后边再加上时区设置就行了。

jdbc.driver=com.mysql.jdbc.driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/books?useunicode=true&characterencoding=utf-8
jdbc.username=root
jdbc.password=12345678
jdbc.maxactive=10
jdbc.maxidle=5

spring-mvc.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
       xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!-- 配置@controller扫描包 -->
    <!--<context:component-scan base-package="cn.book.controller" />-->
    <context:annotation-config/>
    <context:component-scan base-package="cn.book.controller">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.controller"/>
    </context:component-scan>
    <!-- 配置注解驱动,相当于同时使用最新处理器映射跟处理器适配器,对json数据响应提供支持 -->
    <mvc:annotation-driven />
    <mvc:default-servlet-handler/>
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.internalresourceviewresolver">
        <property name="viewclass" value="org.springframework.web.servlet.view.jstlview"/>
        <property name="prefix" value="/web-inf/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

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>

</configuration>

web.xml 这里的最后一部分(有注释的那里)写的是/而不是/*,因为用了后者就把jsp也当静态文件了,访问页面直接显示源代码而不是解析jsp。

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
         xsi:schemalocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <display-name>archetype created web application</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <!-- 配置spring -->
    <context-param>
        <param-name>contextconfiglocation</param-name>
        <param-value>classpath:applicationcontext*.xml</param-value>
    </context-param>
    <!-- 使用监听器加载spring配置文件 -->
    <listener>
        <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>
    </listener>
    <!-- 解决post乱码问题 -->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class>
        <!-- 设置编码参是utf8 -->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 前端控制器 -->
    <servlet>
        <servlet-name>springmvc-web</servlet-name>
        <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>
        <init-param>
            <param-name>contextconfiglocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc-web</servlet-name>
        <url-pattern>/</url-pattern><!--这里写的是/而不是/*,因为用了后者就把jsp也当静态文件了-->
    </servlet-mapping>
</web-app>

然后就是代码

mapper部分:

booksmapper.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="cn.book.mapper.booksmapper">
    <sql id="base_table">
        bookadmin
    </sql>

    <sql id="base_column">
        bid,bn,author,press
    </sql>
    <!--<resultmap id="baseresultmap" type="cn.book.pojo.bookadmin">-->
        <!--<id column="bid" property="bid" jdbctype="integer" />-->
        <!--<result column="bn" property="bn" jdbctype="varchar" />-->
        <!--<result column="author" property="author" jdbctype="varchar" />-->
        <!--<result column="press" property="press" jdbctype="varchar" />-->
    <!--</resultmap>-->
    <insert id="insert" parametertype="bookadmin">
        insert into
        <include refid="base_table"/>
        <trim prefix="(" suffix=")" suffixoverrides=",">
            bn,author,
            <if test="press != null">
                press,
            </if>
        </trim>
        <trim prefix="values(" suffix=")" suffixoverrides=",">
            #{bn,jdbctype=varchar},#{author,jdbctype=varchar},
            <if test="press != null">
                #{press,jdbctype=varchar},
            </if>
        </trim>
    </insert>
    <select id="getbookbybid" resulttype="bookadmin">
        select bid,bn,author,press from bookadmin where bid = #{bid}
    </select>
    <select id="list" resulttype="bookadmin">
        select * from bookadmin
    </select>
    <update id="update" parametertype="bookadmin">
        update
        <include refid="base_table"/>
        set bn = #{bn},author = #{author},press = #{press}
        where bid = #{bid}
    </update>
    <delete id="delete" parametertype="bookadmin">
        delete
        from
        <include refid="base_table"/>
        where bid = #{bid}
    </delete>
    <!--resulttype="bookadmin"-->
</mapper>

booksmapper.java

package cn.book.mapper;

import cn.book.pojo.bookadmin;

import java.util.list;

public interface booksmapper{
    list<bookadmin> list();
    int insert(bookadmin record);
    int update(bookadmin b);
    int delete(bookadmin bid);
    bookadmin getbookbybid(integer bid);
}

pojo实体

bookadmin.java

package cn.book.pojo;

public class bookadmin {
    integer bid;
    string bn;
    string author;
    string press;
    public integer getbid() {
        return bid;
    }
    public void setbid(integer bid) {
        this.bid = bid;
    }
    public string getbn() {
        return bn;
    }
    public void setbn(string bn) {
        this.bn = bn;
    }
    public string getauthor() {
        return author;
    }
    public void setauthor(string author) {
        this.author = author;
    }
    public string getpress() {
        return press;
    }
    public void setpress(string press) {
        this.press = press;
    }
}

service部分

booksservice.java

package cn.book.service;

import cn.book.pojo.bookadmin;
import org.springframework.stereotype.service;

import java.util.list;

@service
public interface booksservice {
    list<bookadmin> list();
    int insertbook(bookadmin bookadmin);
    int update(bookadmin b);
    int deletebookbybid(bookadmin bid);
    bookadmin getbookbybid(int bid);
}

booksserviceimpl.java

package cn.book.service;

import cn.book.mapper.booksmapper;
import cn.book.pojo.bookadmin;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;

import java.util.list;

@service
public class booksserviceimpl implements booksservice {
    @autowired
    private booksmapper booksmapper;
    //    列出数据
    @override
    public list<bookadmin> list(){
        list<bookadmin> list = this.booksmapper.list();
        return list;
    }
    //    插入数据
    @override
    public int insertbook(bookadmin bookadmin){
        return booksmapper.insert(bookadmin);
    }
    //    更新数据
    @override
    public int update(bookadmin b){
        return booksmapper.update(b);
    }
    //    删除数据
    @override
    public int deletebookbybid(bookadmin bid){
        return booksmapper.delete(bid);
    }
    @override
    public bookadmin getbookbybid(int bid){
        return booksmapper.getbookbybid(bid);
    }
}

controller部分

bookscontroller.java

package cn.book.controller;

import cn.book.pojo.bookadmin;
import cn.book.service.booksservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.ui.model;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.servlet.modelandview;

import java.util.list;

@controller
@requestmapping("/a")
public class bookscontroller {
    @autowired
    booksservice booksservice;
    //列出数据表格
    //    设置listbooks页面(list第一种写法)
    @requestmapping("/listbooks")
    public modelandview listbooks(){
        modelandview mav = new modelandview();
        list<bookadmin> bb = booksservice.list();
        mav.addobject("bb",bb);
        mav.setviewname("listbooks");
        return mav;
    }
    //    list的第二种写法
//    @requestmapping("/listbooks")
//    public string listbooks(model model){
//        list<bookadmin> bb = booksservice.list();
//        model.addattribute("bb",bb);
//        return "listbooks";
//    }
    //    添加数据(两部分)
    //    第一步:跳转到这里并添加图书信息,点击添加按钮就执行下边第二段代码
    @requestmapping("/addbooks0")
    public string addbooks0(){
        return "savepage";
    }
    //    第二步:把下边的页面数据返回给后端,再跳转到listbooks页面
    @requestmapping(value = "/addbooks",method = requestmethod.post)
    public string addbooks(bookadmin bookadmin){
        booksservice.insertbook(bookadmin);
        return "redirect:listbooks";
    }
    //    修改数据(两部分)
    //    第一步:更新图书,先通过bid找到图书,并列在/updatepage/{bid}页面上,
    @requestmapping("/updatepage/{bid}")
    public string updatepage(@pathvariable("bid") int bid,model model){
        model.addattribute("bookadmin",booksservice.getbookbybid(bid));
        return "updatepage";
    }
    //    第二步:然后修改即可,在这里点更新提交数据给后端
    @requestmapping(value = "/update",method = requestmethod.post)
    public string update(bookadmin b){
        booksservice.update(b);
        return "redirect:listbooks";
    }
    //    删除图书数据
    @requestmapping("/deletebooksbybid")
    public string deletebooksbybid(bookadmin bid){
        booksservice.deletebookbybid(bid);
        return "redirect:listbooks";
    }
}

jsp页面

listbooks.jsp 列出所有的图书信息(并且包含添加、修改和删除的功能按钮)

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--^^^^^添加对jstl列表的支持^^^^^--%>
<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<html>
<head>
    <title>listbooks</title>
</head>
<body>
<form>
<table align="center" bgcolor="aqua" border="1" cellpadding="0">
    <tr>
        <th width="140">图书bid</th>
        <th width="140">书名</th>
        <th width="140">作者</th>
        <th width="140">出版社</th>
        <th width="140">修改</th>
        <th width="140">删除</th>
    </tr>
    <c:foreach items="${bb}" var="b"> <%--varstatus="ct"--%>
        <tr>
            <td>${b.bid}</td>
            <td>${b.bn}</td>
            <td>${b.author}</td>
            <td>${b.press}</td>
            <td><a href="${pagecontext.request.contextpath}/a/updatepage/${b.bid}">修改</a></td>
            <td><a href="${pagecontext.request.contextpath}/a/deletebooksbybid?bid=${b.bid}" onclick='return confirm("确认要删除吗?")'>删除</a></td>
        </tr>
    </c:foreach>
    <%--<td><a href="${pagecontext.request.contextpath}/a/addbooks0">添加图书(跳转页面)</a></td>--%>
</table>
</form>
<form id="saveform" action="${pagecontext.request.contextpath}/a/addbooks" method="post">
<table align="center" bgcolor="aqua" border="1" cellpadding="0">
    <tr>
        <th width="140">书名</th>
        <th width="140">作者</th>
        <th width="140">出版社</th>
    </tr>
    <tr>
        <td width="140"><input type="text" value="${bookadmin.bn}" name="bn"/></td>
        <td width="140"><input type="text" value="${bookadmin.author}" name="author"/></td>
        <td width="140"><input type="text" value="${bookadmin.press}" name="press" /></td>
        <td width="140"><input type="submit" value="添加" /></td>
    </tr>
</table>
</form>
</body>
</html>

savepage.jsp 添加图书并返回到上边的列表页面

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%
    string path = request.getcontextpath();
    string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/";
%>
<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<html>
<head>
    <title>添加图书</title>
</head>
<body>
<br/>
<form id="saveform" action="${pagecontext.request.contextpath}/a/addbooks" method="post">
    <table  align="center" bgcolor="aqua" border="1" cellpadding="0">
        <tr>
            <td>书名:</td>
            <td><input type="text" value="${bookadmin.bn}" name="bn"/></td>
        </tr>
        <tr>
            <td>作者:</td>
            <td><input type="text" value="${bookadmin.author}" name="author"/></td>
        </tr>
        <tr>
            <td>出版社:</td>
            <td><input type="text" value="${bookadmin.press}" name="press" /></td>
        </tr>
        <input type="submit" value="添加" />
    </table>
</form>
</body>
</html>

updatepage.jsp 更新和修改图书信息

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%
    string path = request.getcontextpath();
    string basepath = request.getscheme() + "://" + request.getservername() + ":" + request.getserverport()
            + path + "/";
%>
<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<html>
<head>
    <title>更新&修改 图书信息</title>
</head>
<body>
<h2>编辑图书信息!</h2>
<form id="updateform" action="${pagecontext.request.contextpath}/a/update" method="post">
    <input type="hidden" value="${bookadmin.bid}" name="bid"/>
    <table  align="center" bgcolor="aqua" border="1" cellpadding="0">
        <tr>
            <td>书名:</td>
            <td><input type="text" value="${bookadmin.bn}" name="bn"/></td>
        </tr>
        <tr>
            <td>作者:</td>
            <td><input type="text" value="${bookadmin.author}" name="author"/></td>
        </tr>
        <tr>
            <td>出版社:</td>
            <td><input type="text" value="${bookadmin.press}" name="press"/></td>
        </tr>
        <input type="submit" value="更新" />
    </table>
</form>
</body>
</html>

然后可以在idea里开一个tomcat来启动项目,实现简单的增删改查功能。

访问http://localhost:8080/springbook_war_exploded/a/listbooks就得到页面:

idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD

项目上传到了github方便查看: 有用的话欢迎加星。

感谢:

controller的详细讲解:https://www.cnblogs.com/pophope/p/5619504.html

https://blog.csdn.net/peng_hong_fu/article/details/53536862

https://www.javatpoint.com/spring-mvc-crud-example

https://www.journaldev.com/3531/spring-mvc-hibernate-mysql-integration-crud-example-tutorial