SSMM(spring+springmvc+maven+mybatis)框架整合

总体流程

  • 启动mysql
    • 启动mysql server(docker版)
    • 启动mysql client(这里使用navicat)
    • 建库
    • 建表
  • 创建mvn项目
    • 手工创建mvn项目
    • 引入spring、springmvc、mybatis以及json相关依赖(即jar)
    • 引入mysql库配置(src/main/resources)
    • 引入spring配置文件(src/main/resources)
    • 创建基本包结构(controller、service、dao、mapper、model)
    • 创建src/main/resources/mapper包,用于放置*Mapper.xml
    • 配置web.xml,使spring生效
  • 使用mybatis-generator创建mybatis的xml文件、mapper层接口、model层
    • 下载mybatis-generator-core-1.3.2.jar和mysql-connector-java-5.1.37.jar,并放置在同一个包例如"mybatis-generator"下

    • 在该包下创建generatorConfig.xml文件并编写
    • 执行生成命令
    • 将model层生成的类拷贝到项目中的model包里
    • 将mapper层生成的接口拷贝到项目中的mapper包里
    • 将生成的xml文件拷贝到src/main/resources/mapper包下
  • 编写dao、service、controller
  • 浏览器或postman测试

一、启动mysql

1、启动docker引擎

  • 双击Docker图标(应用程序)

2、启动mysql server(docker容器)

  • 先删除容器
  • 1 docker rm -f mysql:5.7
  • 再启动容器
  • 1 docker run --name mysql5.7 -e MYSQL_ROOT_PASSWORD=123456 -v /Users/wangna/Desktop/docker-data/mysql/data:/var/lib/mysql -v /Users/wangna/Desktop/docker-data/mysql/file/my.cnf:/etc/my.cnf -p 3306:3306 -d  mysql:5.7

        或者用

  • docker start mysql5.7
  • 检查是否已经启动容器
  • docker ps -a

     

3、启动mysql client(即打开navicat,连接mysql server)

  • 双击"navicat for mysql"图标(应用程序)

4、创建数据库

  • 打开连接(即双击连接)
  • 在连接上右击,创建数据库(前提,该连接内没有该数据库)

5、创建数据表

 

二、创建mvn项目

1、手工创建mvn项目

  • 创建后,先使用mvn clean install构建项目,之后引入eclipse

注意点:

  • war包(即必须有web.xml),这个在之后的springboot中可以去掉(springboot可以直接使用jar包启动web项目)
  • 引入eclipse出错后,查看Problems窗口的提示,一步一步进行修改
  • pom.xml中需要引入properties中需要引入
  • 1     <properties>
    2         <java.version>1.8</java.version>
    3         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    4         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    5     </properties>
    • 第一条:指定jdk版本

    • 后两条:处理中文问题
  • pom.xml中需要引入jdk1.8的maven编译插件
  •  1 <build>
     2         <plugins>
     3             <plugin>
     4                 <groupId>org.apache.maven.plugins</groupId>
     5                 <artifactId>maven-compiler-plugin</artifactId>
     6                 <configuration>
     7                     <source>1.8</source>
     8                     <target>1.8</target>
     9                     <encoding>utf-8</encoding>
    10                 </configuration>
    11             </plugin>
    12         </plugins>
    13     </build>
    View Code

2、在pom.xml文件中引入spring、springmvc、mybatis以及json相关依赖(即jar)

  • spring核心包:core、bean、context
  •  1      <dependency>
     2             <groupId>org.springframework</groupId>
     3             <artifactId>spring-core</artifactId>
     4             <version>${spring.version}</version>
     5         </dependency>
     6         <dependency>
     7             <groupId>org.springframework</groupId>
     8             <artifactId>spring-beans</artifactId>
     9             <version>${spring.version}</version>
    10         </dependency>
    11         <dependency>
    12             <groupId>org.springframework</groupId>
    13             <artifactId>spring-context</artifactId>
    14             <version>${spring.version}</version>
    15         </dependency>
    16     </dependencies>

    别忘了版本:

  • <spring.version>4.2.4.RELEASE</spring.version>
  • springmvc:web、webmvc
  •  1                      <!-- spring mvc -->
     2         <dependency>
     3             <groupId>org.springframework</groupId>
     4             <artifactId>spring-web</artifactId>
     5             <version>${spring.version}</version>
     6         </dependency>
     7         <dependency>
     8             <groupId>org.springframework</groupId>
     9             <artifactId>spring-webmvc</artifactId>
    10             <version>${spring.version}</version>
    11         </dependency>
  • 数据库相关
    • spring-jdbc
    • 1         <dependency>
      2             <groupId>org.springframework</groupId>
      3             <artifactId>spring-jdbc</artifactId>
      4             <version>${spring.version}</version>
      5         </dependency>

       

    • mysql-connector-java(Java连接mysql的必须包)

    • 1         <dependency>
      2             <groupId>mysql</groupId>
      3             <artifactId>mysql-connector-java</artifactId>
      4             <version>5.1.27</version>
      5             <scope>runtime</scope>
      6         </dependency>
  • tomcat-jdbc(数据源,更好的开源实现是druid)
  • 1         <dependency>
    2             <groupId>org.apache.tomcat</groupId>
    3             <artifactId>tomcat-jdbc</artifactId>
    4             <version>7.0.47</version>
    5         </dependency>
  • mybatis:
    • mybatis
    • 1         <dependency>
      2             <groupId>org.mybatis</groupId>
      3             <artifactId>mybatis</artifactId>
      4             <version>${mybatis.version}</version>
      5         </dependency>

      版本:

    • <mybatis.version>3.2.8</mybatis.version>
    • mybatis-spring:mybatis与spring进行集成的包
    • 1         <dependency>
      2             <groupId>org.mybatis</groupId>
      3             <artifactId>mybatis-spring</artifactId>
      4             <version>${mybatis-spring.version}</version>
      5         </dependency>

      版本:

    • <mybatis-spring.version>1.2.2</mybatis-spring.version>
  • json相关(使用Jackson)
    • core
    • annotations
    • databind
  •  1                 <!-- json -->
     2         <dependency>
     3             <groupId>com.fasterxml.jackson.core</groupId>
     4             <artifactId>jackson-annotations</artifactId>
     5             <version>${jackson.version}</version>
     6         </dependency>
     7         <dependency>
     8             <groupId>com.fasterxml.jackson.core</groupId>
     9             <artifactId>jackson-core</artifactId>
    10             <version>${jackson.version}</version>
    11         </dependency>
    12         <dependency>
    13             <groupId>com.fasterxml.jackson.core</groupId>
    14             <artifactId>jackson-databind</artifactId>
    15             <version>${jackson.version}</version>
    16         </dependency>

    版本:

  • <jackson.version>2.6.4</jackson.version>

3、引入mysql库配置(src/main/resources)

jdbc.properties

1 jdbc.driverClassName = com.mysql.jdbc.Driver
2 jdbc.url = jdbc:mysql://localhost:3306/wangna?zeroDateTimeBehavior=convertToNull&amp;useUnicode=true&amp;characterEncoding=utf-8
3 jdbc.username = root
4 jdbc.password = 123456
View Code
  • jdbc.driverClassName:数据库驱动(Java连接数据库必须有的),其中com.mysql.jdbc.Driver来源于mysql-connector-java这个依赖包
  • jdbc.url:
    • 格式:jdbc:mysql://ip:port/数据库名
    • 例:jdbc:mysql://localhost:3306/wn
      • localhost即本地ip,等于127.0.0.1
  • jdbc.username:数据库用户名,默认是root
  • jdbc.password:数据库密码,就是启动mysql容器的命令中的MYSQL_ROOT_PASSWORD的值

4、引入spring配置文件(src/main/resources)

spring.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:mvc="http://www.springframework.org/schema/mvc"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 7                            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 8                            http://www.springframework.org/schema/context 
 9                            http://www.springframework.org/schema/context/spring-context-3.2.xsd
10                            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
11                            
12     <!-- 注解扫描 -->
13     <context:component-scan base-package="com.wn"/>
14     <!-- 启动jackson -->
15     <mvc:annotation-driven />
16     <!-- 引入属性文件 -->
17     <context:property-placeholder location="classpath:jdbc.properties"/>
18     
19     <!-- 引入数据源 -->
20     <bean id="xxxDataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
21         <property name="driverClassName" value="${jdbc.driverClassName}" />
22         <property name="url" value="${jdbc.url}" />
23         <property name="username" value="${jdbc.username}" />
24         <property name="password" value="${jdbc.password}" />
25     </bean>
26     
27     <!-- 引入mybatis -->
28     <bean id="xxxSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
29         <property name="dataSource" ref="xxxDataSource" />
30         <property name="mapperLocations">
31             <list>
32                 <value>classpath*:mapper/*Mapper.xml</value>
33             </list>
34         </property>
35     </bean>
36     <bean id="xxxMapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
37         <property name="basePackage" value="com.wn.mapper" />
38         <property name="sqlSessionFactoryBeanName" value="xxxSqlSessionFactory" />
39     </bean>
40 </beans>
View Code
  • <context:component-scan>:扫描基础包,用于使注解生效,eg.com.wn,那么com.wn及其子包com.wn.*下的注解都会生效
  • <mvc:annotation-driven />:启动jackson,这里注意springmvc自动返回json数据的三步

    • 引入jackson的三个包
    • 启动该注解
    • 在controller层中类或方法上添加@ResponseBody注解
  • context:property-placeholder:将外部文件引入到该文件中,进而在后续的配置中使用外部文件的配置属性,例如:引入jdbc.properties,之后数据源的配置就可以使用jdbc.properties中的属性

  • <bean>
    • 数据源:使用jdbc.properties中的四个属性进行构建,其中org.apache.tomcat.jdbc.pool.DataSource来源于tomcat-jdbc这个依赖包
    • sqlSessionFactory:mybatis的部分,需要根据之前创建的数据源以及将要扫描的Mapper.xml来创建,其中org.mybatis.spring.SqlSessionFactoryBean来源于mybatis-spring依赖包
    • MapperScannerConfigurer:mybatis的部分,需要根据之前创建的sqlSessionFactory和mapper层接口的包(见5)

5、创建基本包(package)结构(controller、service、dao、mapper、model)

  • eg.com.wn.controller,这里的基础包com.wn与spring.xml中的<context:component-scan>一样

6、创建src/main/resources/mapper的folder包,用于放置*Mapper.xml

  • 这里的src/main/resources/mapper/*Mapper.xml与spring.xml中的xxxSqlSessionFactory的mapperLocations的值classpath*:mapper/*Mapper.xml一样

7、配置web.xml,使spring生效

 1     <servlet>
 2         <servlet-name>dispatcherServlet</servlet-name>
 3         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 4         <init-param>
 5             <param-name>contextConfigLocation</param-name>
 6             <param-value>classpath*:spring*.xml</param-value>
 7         </init-param>
 8         <load-on-startup>1</load-on-startup>
 9     </servlet>
10     <servlet-mapping>
11         <servlet-name>dispatcherServlet</servlet-name>
12         <url-pattern>/</url-pattern>
13     </servlet-mapping>
14 
15     <filter>
16         <filter-name>encodingFilter</filter-name>
17         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
18         <init-param>
19             <param-name>encoding</param-name>
20             <param-value>UTF-8</param-value>
21         </init-param>
22         <init-param>
23             <param-name>forceEncoding</param-name>
24             <param-value>true</param-value>
25         </init-param>
26     </filter>
27     <filter-mapping>
28         <filter-name>encodingFilter</filter-name>
29         <url-pattern>/*</url-pattern>
30     </filter-mapping>
View Code
  • 设置DispatcherServlet
    • 指定spring配置文件(即上述的spring.xml)所在的位置与名称
    • 指定该servlet的扫描路径为根路径"/",即该项目下的所有请求都会被DispatcherServlet所拦截并分发到相应的controller类中的方法上
  • 配置CharacterEncodingFilter:处理中文问题

 

三、使用mybatis-generator创建mybatis的xml文件、mapper层接口、model层

1、下载mybatis-generator-core-1.3.2.jar和mysql-connector-java-5.1.37.jar,并放置在同一个包例如"mybatis-generator"下

2、在该包下创建generatorConfig.xml文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE generatorConfiguration
 3   PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
 4   "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
 5 <generatorConfiguration>
 6     <!--数据库驱动-->
 7     <classPathEntry    location="mysql-connector-java-5.1.37.jar"/>
 8     <context id="mysql">
 9         <!-- 用于防止生成大量注释 -->
10         <commentGenerator>
11             <property name="suppressDate" value="true"/>
12             <property name="suppressAllComments" value="true"/>
13         </commentGenerator>
14         <!--数据库链接地址账号密码-->
15         <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/wn" userId="root" password="123456">
16         </jdbcConnection>
17         <javaTypeResolver>
18             <property name="forceBigDecimals" value="false"/>
19         </javaTypeResolver>
20         <!--生成Model类存放位置-->
21         <javaModelGenerator targetPackage="com.wn.model" targetProject="xxx">
22             <property name="enableSubPackages" value="true"/>
23             <property name="trimStrings" value="true"/>
24         </javaModelGenerator>
25         <!--生成映射文件存放位置-->
26         <sqlMapGenerator targetPackage="njkj" targetProject="xxx">
27             <property name="enableSubPackages" value="true"/>
28         </sqlMapGenerator>
29         <!--生成mapper接口存放位置-->
30         <javaClientGenerator type="XMLMAPPER" targetPackage="com.wn.mapper" targetProject="xxx">
31             <property name="enableSubPackages" value="true"/>
32         </javaClientGenerator>
33         <!--生成对应表及类名-->
34         <table tableName="t_book" domainObjectName="Book" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">  
35         </table>
36 
37     </context>
38 </generatorConfiguration>
View Code

说明:每一条的含义参见http://www.cnblogs.com/java-zhao/p/5569714.html

3、执行命令(在"mybatis-generator"包下)

  • 进入"mybatis-generator"包
  • 创建xxx包
  • java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite

4、将生成的类、接口、xml拷贝到项目中

  • 将model层生成的类拷贝到项目中的model包里
  •  1 package com.wn.model;
     2 
     3 import java.util.Date;
     4 
     5 public class Book {
     6     private Integer id;
     7 
     8     private String bookName;
     9 
    10     private String author;
    11 
    12     private Date publishDate;
    13 
    14     public Integer getId() {
    15         return id;
    16     }
    17 
    18     public void setId(Integer id) {
    19         this.id = id;
    20     }
    21 
    22     public String getBookName() {
    23         return bookName;
    24     }
    25 
    26     public void setBookName(String bookName) {
    27         this.bookName = bookName == null ? null : bookName.trim();
    28     }
    29 
    30     public String getAuthor() {
    31         return author;
    32     }
    33 
    34     public void setAuthor(String author) {
    35         this.author = author == null ? null : author.trim();
    36     }
    37 
    38     public Date getPublishDate() {
    39         return publishDate;
    40     }
    41 
    42     public void setPublishDate(Date publishDate) {
    43         this.publishDate = publishDate;
    44     }
    45 }
    View Code
  • 将mapper层生成的接口拷贝到项目中的mapper包里
  •  1 package com.wn.mapper;
     2 
     3 import com.wn.model.Book;
     4 
     5 public interface BookMapper {
     6     int deleteByPrimaryKey(Integer id);
     7 
     8     int insert(Book record);
     9 
    10     int insertSelective(Book record);
    11 
    12     Book selectByPrimaryKey(Integer id);
    13 
    14     int updateByPrimaryKeySelective(Book record);
    15 
    16     int updateByPrimaryKey(Book record);
    17 }
    View Code
  • 将生成的xml文件拷贝到src/main/resources/mapper包下
  •  1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
     3 <mapper namespace="com.wn.mapper.BookMapper">
     4     <resultMap id="BaseResultMap" type="com.wn.model.Book">
     5         <id column="id" property="id" jdbcType="INTEGER" />
     6         <result column="book_name" property="bookName" jdbcType="VARCHAR" />
     7         <result column="author" property="author" jdbcType="VARCHAR" />
     8         <result column="publish_date" property="publishDate" jdbcType="TIMESTAMP" />
     9     </resultMap>
    10     <sql id="Base_Column_List">
    11         id, book_name, author, publish_date
    12     </sql>
    13     <select id="selectByPrimaryKey" resultMap="BaseResultMap"
    14         parameterType="java.lang.Integer">
    15         select
    16         <include refid="Base_Column_List" />
    17         from t_book
    18         where id = #{id,jdbcType=INTEGER}
    19     </select>
    20     <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    21         delete from t_book
    22         where id = #{id,jdbcType=INTEGER}
    23     </delete>
    24     <insert id="insert" parameterType="com.wn.model.Book">
    25         insert into t_book (id, book_name, author,
    26         publish_date)
    27         values (#{id,jdbcType=INTEGER}, #{bookName,jdbcType=VARCHAR},
    28         #{author,jdbcType=VARCHAR},
    29         #{publishDate,jdbcType=TIMESTAMP})
    30     </insert>
    31     <insert id="insertSelective" parameterType="com.wn.model.Book">
    32         insert into t_book
    33         <trim prefix="(" suffix=")" suffixOverrides=",">
    34             <if test="id != null">
    35                 id,
    36             </if>
    37             <if test="bookName != null">
    38                 book_name,
    39             </if>
    40             <if test="author != null">
    41                 author,
    42             </if>
    43             <if test="publishDate != null">
    44                 publish_date,
    45             </if>
    46         </trim>
    47         <trim prefix="values (" suffix=")" suffixOverrides=",">
    48             <if test="id != null">
    49                 #{id,jdbcType=INTEGER},
    50             </if>
    51             <if test="bookName != null">
    52                 #{bookName,jdbcType=VARCHAR},
    53             </if>
    54             <if test="author != null">
    55                 #{author,jdbcType=VARCHAR},
    56             </if>
    57             <if test="publishDate != null">
    58                 #{publishDate,jdbcType=TIMESTAMP},
    59             </if>
    60         </trim>
    61     </insert>
    62     <update id="updateByPrimaryKeySelective" parameterType="com.wn.model.Book">
    63         update t_book
    64         <set>
    65             <if test="bookName != null">
    66                 book_name = #{bookName,jdbcType=VARCHAR},
    67             </if>
    68             <if test="author != null">
    69                 author = #{author,jdbcType=VARCHAR},
    70             </if>
    71             <if test="publishDate != null">
    72                 publish_date = #{publishDate,jdbcType=TIMESTAMP},
    73             </if>
    74         </set>
    75         where id = #{id,jdbcType=INTEGER}
    76     </update>
    77     <update id="updateByPrimaryKey" parameterType="com.wn.model.Book">
    78         update t_book
    79         set book_name = #{bookName,jdbcType=VARCHAR},
    80         author = #{author,jdbcType=VARCHAR},
    81         publish_date = #{publishDate,jdbcType=TIMESTAMP}
    82         where id = #{id,jdbcType=INTEGER}
    83     </update>
    84 </mapper>
    View Code
    • namespace="com.wn.mapper.BookMapper":namespace的值必须是生成的mapper接口的全类名
    • resultMap
      • 作用:对应数据库表与生成的model类的属性对应关系
      • resultMap下的type="com.wn.model.Book"必须是生成的model类的全类名
    • select
      • id:一定是mapper接口的方法名,eg。也就是说,当dao调用mapper接口中的selectByPrimaryKey的时候,该方法会自动调用BookMapper.xml中的id=selectByPrimaryKey下的语句,或者说,BookMapper.xml就是BookMapper接口的实现类
      • resultMap:返回值类型,还有一个是resultType(作业?
      • parameterType:参数(入参)类型
      • 获取入参用#{id}
    • delete
      • id:同上
    • insert
    • update
    • updateSelective
      • <set>标签:做了两件事
        • 添加了set
        • 去掉尾部的","

 

四、编写dao、service、controller

1、BookDao

 1 package com.wn.dao;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Repository;
 5 
 6 import com.wn.mapper.BookMapper;
 7 import com.wn.model.Book;
 8 
 9 @Repository
10 public class BookDao {
11     @Autowired
12     private BookMapper bookMapper;
13 
14     // 添加
15     public boolean add(Book book) {
16         return bookMapper.insert(book) == 1 ? true : false;
17     }
18 
19     // 显示
20     public Book selectById(Integer id) {
21         return bookMapper.selectByPrimaryKey(id);
22     }
23 
24     // 删除
25     public boolean deleteById(Integer id) {
26         return bookMapper.deleteByPrimaryKey(id) == 1 ? true : false;
27     }
28 
29     // 修改
30     public boolean updateById(Book book) {
31         return bookMapper.updateByPrimaryKey(book) == 1 ? true : false;
32     }
33 }

2、BookService

 1 package com.wn.service;
 2 
 3 import java.util.Date;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Service;
 7 
 8 import com.wn.dao.BookDao;
 9 import com.wn.model.Book;
10 
11 @Service
12 public class BookService {
13     @Autowired
14     private BookDao bookDao;
15 
16     // 添加
17     public boolean addBook(String bookName, String author, Date publishDate) {
18         Book book = new Book();
19         book.setBookName(bookName);
20         book.setAuthor(author);
21         book.setPublishDate(publishDate);
22 
23         return bookDao.add(book);
24     }
25 
26     // 显示
27     public Book getBook(Integer id) {
28         return bookDao.selectById(id);
29     }
30 
31     // 删除
32     public boolean deleteBook(Integer id) {
33         return bookDao.deleteById(id);
34     }
35 
36     // 修改
37     public boolean updateBook(Integer id, String bookName, String author, Date publishDate) {
38         Book book = getBook(id);
39         book.setBookName(bookName);
40         book.setAuthor(author);
41         book.setPublishDate(publishDate);
42 
43         return bookDao.updateById(book);
44     }
45 }

3、BookController

 1 package com.wn.controller;
 2 
 3 import java.text.ParseException;
 4 import java.util.Date;
 5 
 6 import org.apache.commons.lang3.time.DateFormatUtils;
 7 import org.apache.commons.lang3.time.DateUtils;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.format.annotation.DateTimeFormat;
10 import org.springframework.web.bind.annotation.PathVariable;
11 import org.springframework.web.bind.annotation.RequestMapping;
12 import org.springframework.web.bind.annotation.RequestMethod;
13 import org.springframework.web.bind.annotation.RequestParam;
14 import org.springframework.web.bind.annotation.RestController;
15 
16 import com.wn.model.Book;
17 import com.wn.resp.BookResp;
18 import com.wn.service.BookService;
19 
20 @RestController
21 @RequestMapping("/book")
22 public class BookController {
23     @Autowired
24     private BookService bookService;
25 
26     // 添加
27     @RequestMapping(value = "/add", method = RequestMethod.POST)
28     public boolean addBook(@RequestParam("bookName") String bookName, @RequestParam("author") String author,
29             @RequestParam("publishDate") String publishDateStr) {
30         try {
31             Date publishDate = DateUtils.parseDate(publishDateStr, "yyyy-MM-dd HH:mm:ss");
32             return bookService.addBook(bookName, author, publishDate);
33         } catch (ParseException e) {
34             e.printStackTrace();
35         }
36         return false;
37     }
38 
39     @RequestMapping(value = "/add2", method = RequestMethod.POST)
40     public boolean addBook2(@RequestParam("bookName") String bookName, @RequestParam("author") String author,
41             @RequestParam("publishDate") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date publishDate) {
42         return bookService.addBook(bookName, author, publishDate);
43     }
44 
45     // 显示
46     @RequestMapping(value = "/{id}", method = RequestMethod.GET)
47     public BookResp getBook(@PathVariable("id") Integer id) {
48         Book book = bookService.getBook(id);
49         String dateStr = DateFormatUtils.format(book.getPublishDate(), "yyyy-MM-dd HH:mm:ss");
50         BookResp resp = new BookResp();
51         resp.setId(book.getId());
52         resp.setAuthor(book.getAuthor());
53         resp.setBookName(book.getBookName());
54         resp.setPublishDate(dateStr);
55         return resp;
56     }
57 
58     // 删除 被注释的是删除方法一
59     // @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
60     // public boolean deleteBook(@RequestParam("id") Integer id) {
61     // return bookService.deleteBook(id);
62     // }
63 
64     @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
65     public boolean deleteBook(@PathVariable("id") Integer id) {
66         return bookService.deleteBook(id);
67     }
68 
69     // 修改
70     @RequestMapping(value = "/update", method = RequestMethod.PUT)
71     public boolean updateBook(@RequestParam("id") Integer id, @RequestParam("bookName") String bookName,
72             @RequestParam("author") String author,
73             @RequestParam("publishDate") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date publishDate) {
74         return bookService.updateBook(id, bookName, author, publishDate);
75     }
76 }

为了解决日期问题

 1 package com.wn.resp;
 2 
 3 public class BookResp {
 4     private Integer id;
 5 
 6     private String bookName;
 7 
 8     private String author;
 9 
10     private String publishDate;
11 
12     public Integer getId() {
13         return id;
14     }
15 
16     public void setId(Integer id) {
17         this.id = id;
18     }
19 
20     public String getBookName() {
21         return bookName;
22     }
23 
24     public void setBookName(String bookName) {
25         this.bookName = bookName == null ? null : bookName.trim();
26     }
27 
28     public String getAuthor() {
29         return author;
30     }
31 
32     public void setAuthor(String author) {
33         this.author = author == null ? null : author.trim();
34     }
35 
36     public String getPublishDate() {
37         return publishDate;
38     }
39 
40     public void setPublishDate(String publishDate) {
41         this.publishDate = publishDate;
42     }
43 }

五、浏览器或postman测试(举例用postman测试)

1、添加

成功会返回true

2、显示

成功返回json串:

1 {
2   "id": 3,
3   "bookName": "PE",
4   "author": "dawei",
5   "publishDate": "2014-11-08 11:11:11"
6 }

3、删除

成功返回true,另一种方法如下:

4、修改

 

posted @ 2016-11-14 17:20  王小霞  阅读(927)  评论(0编辑  收藏  举报