[JAVA] SpringMVC整合SSM实现表现层数据封装详解

2370 0
王子 2022-11-9 09:39:45 | 显示全部楼层 |阅读模式
目录

    SSM整合配置
      SSM整合流程
    Spring整合MybatisSpring整合SpringMVC功能模块开发接口测试表现层数据封装(前后端通信协议)
      表现层响应数据的问题定义Result类封装响应结果表现层数据封装返回Result对象



SSM整合配置


SSM整合流程

1.创建工程
2.SSM整合
Spring
    SpringConfig
MyBatis
    MybatisConfigJdbcConfigjdbc.properties
SpringMVC
    ServletConfigSpringMvcConfig
3.功能模块
表与实体类
dao(接口+自动代理)
service(接口+实现类)
    业务层接口测试(整合JUnit)
controller
    表现层接口测试(PostMan)
SSM整合配置
创建工程,添加依赖和插件
  1. <dependencies>
  2.     <dependency>
  3.         <groupId>org.springframework</groupId>
  4.         <artifactId>spring-webmvc</artifactId>
  5.         <version>5.2.10.RELEASE</version>
  6.     </dependency>
  7.     <dependency>
  8.         <groupId>org.springframework</groupId>
  9.         <artifactId>spring-jdbc</artifactId>
  10.         <version>5.2.10.RELEASE</version>
  11.     </dependency>
  12.     <dependency>
  13.         <groupId>org.springframework</groupId>
  14.         <artifactId>spring-test</artifactId>
  15.         <version>5.2.10.RELEASE</version>
  16.     </dependency>
  17.     <dependency>
  18.         <groupId>org.mybatis</groupId>
  19.         <artifactId>mybatis</artifactId>
  20.         <version>3.5.6</version>
  21.     </dependency>
  22.     <dependency>
  23.         <groupId>org.mybatis</groupId>
  24.         <artifactId>mybatis-spring</artifactId>
  25.         <version>1.3.0</version>
  26.     </dependency>
  27.     <dependency>
  28.         <groupId>mysql</groupId>
  29.         <artifactId>mysql-connector-java</artifactId>
  30.         <version>5.1.47</version>
  31.     </dependency>
  32.     <dependency>
  33.         <groupId>com.alibaba</groupId>
  34.         <artifactId>druid</artifactId>
  35.         <version>1.1.16</version>
  36.     </dependency>
  37.     <dependency>
  38.         <groupId>junit</groupId>
  39.         <artifactId>junit</artifactId>
  40.         <version>4.12</version>
  41.         <scope>test</scope>
  42.     </dependency>
  43.     <dependency>
  44.         <groupId>javax.servlet</groupId>
  45.         <artifactId>javax.servlet-api</artifactId>
  46.         <version>3.1.0</version>
  47.         <scope>provided</scope>
  48.     </dependency>
  49.     <dependency>
  50.         <groupId>com.fasterxml.jackson.core</groupId>
  51.         <artifactId>jackson-databind</artifactId>
  52.         <version>2.9.0</version>
  53.     </dependency>
  54.     <dependency>
  55.       <groupId>org.projectlombok</groupId>
  56.       <artifactId>lombok</artifactId>
  57.       <version>1.18.24</version>
  58.     </dependency>
  59. </dependencies>
  60. <build>
  61.     <plugins>
  62.         <plugin>
  63.             <groupId>org.apache.tomcat.maven</groupId>
  64.             <artifactId>tomcat7-maven-plugin</artifactId>
  65.             <version>2.1</version>
  66.             <configuration>
  67.                 <port>80</port>
  68.                 <path>/</path>
  69.             </configuration>
  70.         </plugin>
  71.     </plugins>
  72. </build>
复制代码
Spring整合Mybatis

创建数据库和表
  1. -- 创建db5数据库
  2. CREATE DATABASE IF NOT EXISTS db5 CHARACTER SET utf8;
  3. -- 使用db5数据库
  4. USE db5;
  5. -- 创建tbl_book表
  6. CREATE TABLE tbl_book(
  7.     id INT PRIMARY KEY AUTO_INCREMENT, -- 图书编号
  8.     TYPE VARCHAR(100), -- 图书类型
  9.     NAME VARCHAR(100), -- 图书名称
  10.     description VARCHAR(100) -- 图书描述
  11. );
  12. -- 添加初始化数据
  13. INSERT INTO tbl_book VALUES(NULL,'图书类型一','图书名称一','图书描述一');
  14. INSERT INTO tbl_book VALUES(NULL,'图书类型二','图书名称二','图书描述二');
  15. INSERT INTO tbl_book VALUES(NULL,'图书类型三','图书名称三','图书描述三');
  16. INSERT INTO tbl_book VALUES(NULL,'图书类型四','图书名称四','图书描述四');
  17. INSERT INTO tbl_book VALUES(NULL,'图书类型五','图书名称五','图书描述五');
  18. INSERT INTO tbl_book VALUES(NULL,'图书类型六','图书名称六','图书描述六');
复制代码
jdbc.properties属性文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db5
jdbc.username=root
jdbc.password=123456
JdbcConfig配置类
  1. public class JdbcConfig {
  2.     @Value("${jdbc.driver}")
  3.     private String driver;
  4.     @Value("${jdbc.url}")
  5.     private String url;
  6.     @Value("${jdbc.username}")
  7.     private String username;
  8.     @Value("${jdbc.password}")
  9.     private String password;
  10.     //配置连接池
  11.     @Bean
  12.     public DataSource dataSource(){
  13.         DruidDataSource dataSource = new DruidDataSource();
  14.         dataSource.setDriverClassName(driver);
  15.         dataSource.setUrl(url);
  16.         dataSource.setUsername(username);
  17.         dataSource.setPassword(password);
  18.         return dataSource;
  19.     }
  20.     //Spring事务管理需要的平台事务管理器对象
  21.     @Bean
  22.     public PlatformTransactionManager transactionManager(DataSource dataSource){
  23.         DataSourceTransactionManager ds = new DataSourceTransactionManager();
  24.         ds.setDataSource(dataSource);
  25.         return ds;
  26.     }
  27. }
复制代码
MybatisConfig配置类
  1. public class MyBatisConfig {
  2.     @Bean
  3.     public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
  4.         SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
  5.         factoryBean.setDataSource(dataSource);
  6.         factoryBean.setTypeAliasesPackage("com.moming.domain");
  7.         return factoryBean;
  8.     }
  9.     @Bean
  10.     public MapperScannerConfigurer mapperScannerConfigurer(){
  11.         MapperScannerConfigurer msc = new MapperScannerConfigurer();
  12.         msc.setBasePackage("com.moming.dao");
  13.         return msc;
  14.     }
  15. }
复制代码
SpringConfig配置类
  1. @Configuration
  2. @ComponentScan({"com.moming.service"})
  3. @PropertySource("classpath:jdbc.properties")
  4. @Import({JdbcConfig.class,MyBatisConfig.class})
  5. @EnableTransactionManagement //开启Spring事务管理
  6. public class SpringConfig {
  7. }
复制代码
Spring整合SpringMVC

SpringMvcConfig配置类
  1. @Configuration
  2. @ComponentScan("com.moming.controller")
  3. @EnableWebMvc
  4. public class SpringMvcConfig {
  5. }
复制代码
ServletConfig配置类,加载SpringMvcConfig和SpringConfig配置类
  1. public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
  2.     protected Class<?>[] getRootConfigClasses() {
  3.         return new Class[]{SpringConfig.class};
  4.     }
  5.     protected Class<?>[] getServletConfigClasses() {
  6.         return new Class[]{SpringMvcConfig.class};
  7.     }
  8.     protected String[] getServletMappings() {
  9.         return new String[]{"/"};
  10.     }
  11.     //乱码处理
  12.     @Override
  13.     protected Filter[] getServletFilters() {
  14.         CharacterEncodingFilter filter = new CharacterEncodingFilter();
  15.         filter.setEncoding("UTF-8");
  16.         return new Filter[]{filter};
  17.     }
  18. }
复制代码
功能模块开发

数据层开发(BookDao)
Book实体类
  1. @Data
  2. public class Book {
  3.     private Integer id;
  4.     private String type;
  5.     private String name;
  6.     private String description;
  7. }
复制代码
BookDao接口
  1. public interface BookDao {
  2.     //@Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
  3.     @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
  4.     public int save(Book book);  //返回值表示影响的行数
  5.     @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
  6.     public int update(Book book);
  7.     @Delete("delete from tbl_book where id = #{id}")
  8.     public int delete(Integer id);
  9.     @Select("select * from tbl_book where id = #{id}")
  10.     public Book getById(Integer id);
  11.     @Select("select * from tbl_book")
  12.     public List<Book> getAll();
  13. }
复制代码
业务层开发(BookService/BookServiceImpl)
BookService接口
  1. @Transactional //表示所有方法进行事务管理
  2. public interface BookService {
  3.     /**
  4.      * 保存
  5.      * @param book
  6.      * @return
  7.      */
  8.     public boolean save(Book book);
  9.     /**
  10.      * 修改
  11.      * @param book
  12.      * @return
  13.      */
  14.     public boolean update(Book book);
  15.     /**
  16.      * 根据id删除
  17.      * @param id
  18.      * @return
  19.      */
  20.     public boolean delete(Integer id);
  21.     /**
  22.      * 按id查询
  23.      * @param id
  24.      * @return
  25.      */
  26.     public Book getById(Integer id);
  27.     /**
  28.      * 查询全部
  29.      * @return
  30.      */
  31.     public List<Book> getAll();
  32. }
复制代码
BookServiceImpl实现类
  1. @Service
  2. public class BookServiceImpl implements BookService {
  3.     @Autowired
  4.     private BookDao bookDao;
  5.     public boolean save(Book book) {
  6.         bookDao.save(book);
  7.         return true;
  8.     }
  9.     public boolean update(Book book) {
  10.         bookDao.update(book);
  11.         return true;
  12.     }
  13.     public boolean delete(Integer id) {
  14.         bookDao.delete(id);
  15.         return true;
  16.     }
  17.     public Book getById(Integer id) {
  18.         return bookDao.getById(id);
  19.     }
  20.     public List<Book> getAll() {
  21.         return bookDao.getAll();
  22.     }
  23. }
复制代码
表现层开发(BookController)
  1. @RestController
  2. @RequestMapping("/books")
  3. public class BookController {
  4.     @Autowired
  5.     private BookService bookService;
  6.     @PostMapping
  7.     public boolean save(@RequestBody Book book) {
  8.         return bookService.save(book);
  9.     }
  10.     @PutMapping
  11.     public boolean update(@RequestBody Book book) {
  12.         return bookService.update(book);
  13.     }
  14.     @DeleteMapping("/{id}")
  15.     public boolean delete(@PathVariable Integer id) {
  16.         return bookService.delete(id);
  17.     }
  18.     @GetMapping("/{id}")
  19.     public Book getById(@PathVariable Integer id) {
  20.         return bookService.getById(id);
  21.     }
  22.     @GetMapping
  23.     public List<Book> getAll() {
  24.         return bookService.getAll();
  25.     }
  26. }
复制代码
接口测试

Spring整合Junit测试业务层方法
  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(classes = SpringConfig.class)
  3. public class BookServiceTest {
  4.     @Autowired
  5.     private BookService bookService;
  6.     @Test
  7.     public void testGetById(){
  8.         Book book = bookService.getById(1);
  9.         System.out.println(book);
  10.     }
  11.     @Test
  12.     public void testGetAll(){
  13.         List<Book> all = bookService.getAll();
  14.         System.out.println(all);
  15.     }
  16. }
复制代码


postman测试表现层接口
测试保存图书





表现层数据封装(前后端通信协议)


表现层响应数据的问题

问题:我们表现层增删改方法返回true或者false表示是否成功,getById()方法返回一个json对象,getAll()方法返回一个json对象数组,这里就出现了三种格式的响应结果,极其不利于前端解析。


解决:我们需要统一响应结果的格式



定义Result类封装响应结果

controller/Result类封装响应结果
  1. @Data
  2. public class Result {
  3.     //描述统一格式中的数据
  4.     private Object data;
  5.     //描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功失败
  6.     private Integer code;
  7.     //描述统一格式中的消息,可选属性
  8.     private String msg;
  9.     public Result() {
  10.     }
  11.     public Result(Integer code,Object data) {
  12.         this.data = data;
  13.         this.code = code;
  14.     }
  15.     public Result(Integer code, Object data, String msg) {
  16.         this.data = data;
  17.         this.code = code;
  18.         this.msg = msg;
  19.     }
  20. }
复制代码
注意事项:Result类中的字段并不是固定的,可以根据需要自行增减
controller/Code类封装响应码
  1. //状态码
  2. public class Code {
  3.     public static final Integer SAVE_OK = 20011;
  4.     public static final Integer DELETE_OK = 20021;
  5.     public static final Integer UPDATE_OK = 20031;
  6.     public static final Integer GET_OK = 20041;
  7.     public static final Integer SAVE_ERR = 20010;
  8.     public static final Integer DELETE_ERR = 20020;
  9.     public static final Integer UPDATE_ERR = 20030;
  10.     public static final Integer GET_ERR = 20040;
  11. }
复制代码
注意事项:Code类的常量设计也不是固定的,可以根据需要自行增减,例如将查询再进行细分为GET_OK,GET_ALL_OK,GET_PAGE_OK

表现层数据封装返回Result对象
  1. @RestController
  2. @RequestMapping("/books")
  3. public class BookController {
  4.     @Autowired
  5.     private BookService bookService;
  6.     @PostMapping
  7.     public Result save(@RequestBody Book book) {
  8.         boolean flag = bookService.save(book);
  9.         return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
  10.     }
  11.     @PutMapping
  12.     public Result update(@RequestBody Book book) {
  13.         boolean flag = bookService.update(book);
  14.         return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
  15.     }
  16.     @DeleteMapping("/{id}")
  17.     public Result delete(@PathVariable Integer id) {
  18.         boolean flag = bookService.delete(id);
  19.         return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
  20.     }
  21.     @GetMapping("/{id}")
  22.     public Result getById(@PathVariable Integer id) {
  23.         Book book = bookService.getById(id);
  24.         Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
  25.         String msg = book != null ? "" : "数据查询失败,请重试!";
  26.         return new Result(code,book,msg);
  27.     }
  28.     @GetMapping
  29.     public Result getAll() {
  30.         List<Book> bookList = bookService.getAll();
  31.         Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
  32.         String msg = bookList != null ? "" : "数据查询失败,请重试!";
  33.         return new Result(code,bookList,msg);
  34.     }
  35. }
复制代码
Postman测试




到此这篇关于SpringMVC整合SSM实现表现层数据封装详解的文章就介绍到这了,更多相关SpringMVC表现层数据封装内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行