写点什么

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

发布于: 2020 年 05 月 01 日

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



工作环境:



  • Windows 10

  • jdk8(1.8)

  • IntelliJ IDEA 

  • spring 4 和 springMVC

  • MySQL 5.7

  • maven 3.3

  • mybatis 3.4

  • DBCP

  • Tomcat 8.5



项目上传到了Github方便查看:https://github.com/finch-xu/springbook/tree/0.9 有用的话欢迎加星。



页面演示:





首先新建项目



如图所示新建maven的webapp



建数据库和数据表



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;



这里是项目目录结构



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 找不到的包可以去https://mvnrepository.com/ 这里找,很方便的。



<?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就得到页面:



项目上传到了Github方便查看:https://github.com/finch-xu/springbook/tree/0.9 有用的话欢迎加星。



转载需注明本文地址:https://my.oschina.net/finchxu/blog/3007984



感谢:



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



发布于: 2020 年 05 月 01 日阅读数: 50
用户头像

还未添加个人签名 2018.07.11 加入

还未添加个人简介

评论

发布
暂无评论
idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD