• SpringMVC(四):SSM整合


    目录

    一、SSM整合

    1、整合配置

    2、功能模块

    3、接口测试

    二、表现层数据封装

    1、整合中响应数据问题

    2、定义Result类封装响应结果

    3、表现层数据封装返回Result对象


    一、SSM整合

    1、整合配置

    (1)创建web工程,添加依赖和插件

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.springframeworkgroupId>
    4. <artifactId>spring-webmvcartifactId>
    5. <version>5.2.10.RELEASEversion>
    6. dependency>
    7. <dependency>
    8. <groupId>org.springframeworkgroupId>
    9. <artifactId>spring-jdbcartifactId>
    10. <version>5.2.10.RELEASEversion>
    11. dependency>
    12. <dependency>
    13. <groupId>org.springframeworkgroupId>
    14. <artifactId>spring-testartifactId>
    15. <version>5.2.10.RELEASEversion>
    16. dependency>
    17. <dependency>
    18. <groupId>org.mybatisgroupId>
    19. <artifactId>mybatisartifactId>
    20. <version>3.5.6version>
    21. dependency>
    22. <dependency>
    23. <groupId>org.mybatisgroupId>
    24. <artifactId>mybatis-springartifactId>
    25. <version>1.3.0version>
    26. dependency>
    27. <dependency>
    28. <groupId>mysqlgroupId>
    29. <artifactId>mysql-connector-javaartifactId>
    30. <version>5.1.47version>
    31. dependency>
    32. <dependency>
    33. <groupId>com.alibabagroupId>
    34. <artifactId>druidartifactId>
    35. <version>1.1.16version>
    36. dependency>
    37. <dependency>
    38. <groupId>junitgroupId>
    39. <artifactId>junitartifactId>
    40. <version>4.12version>
    41. <scope>testscope>
    42. dependency>
    43. <dependency>
    44. <groupId>javax.servletgroupId>
    45. <artifactId>javax.servlet-apiartifactId>
    46. <version>3.1.0version>
    47. <scope>providedscope>
    48. dependency>
    49. <dependency>
    50. <groupId>com.fasterxml.jackson.coregroupId>
    51. <artifactId>jackson-databindartifactId>
    52. <version>2.9.0version>
    53. dependency>
    54. dependencies>
    55. <build>
    56. <plugins>
    57. <plugin>
    58. <groupId>org.apache.tomcat.mavengroupId>
    59. <artifactId>tomcat7-maven-pluginartifactId>
    60. <version>2.1version>
    61. <configuration>
    62. <port>80port>
    63. <path>/path>
    64. configuration>
    65. plugin>
    66. plugins>
    67. build>

    (2)spring整合mybatis

    创建数据库和表

    1. -- 创建ssm_db数据库
    2. CREATE DATABASE IF NOT EXISTS ssm_db CHARACTER SET utf8;
    3. -- 使用ssm_db数据库
    4. USE ssm_db;
    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,'计算机理论','Spring实战 第5版','Spring入门经典教材,深入理解Spring原理技术内幕');
    14. INSERT INTO tbl_book VALUES(NULL,'计算机理论','Spring 5核心原理与30个类手写实战','十年沉淀之作,手写Spring精华思想');
    15. INSERT INTO tbl_book VALUES(NULL,'计算机理论','Spring 5设计模式','深入Spring源码剖析,Spring源码蕴含的10大设计模式');
    16. INSERT INTO tbl_book VALUES(NULL,'市场营销','直播就该这么做:主播高效沟通实战指南','李子柒、李佳琦、薇娅成长为网红的秘密都在书中');
    17. INSERT INTO tbl_book VALUES(NULL,'市场营销','直播销讲实战一本通','和秋叶一起学系列网络营销书籍');
    18. INSERT INTO tbl_book VALUES(NULL,'市场营销','直播带货:淘宝、天猫直播从新手到高手','一本教你如何玩转直播的书,10堂课轻松实现带货月入3W+');

     jdbc.properties属性文件

    1. jdbc.driver=com.mysql.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/ssm_db
    3. jdbc.username=root
    4. jdbc.password=root

    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.itheima.domain");
    7. return factoryBean;
    8. }
    9. @Bean
    10. public MapperScannerConfigurer mapperScannerConfigurer(){
    11. MapperScannerConfigurer msc = new MapperScannerConfigurer();
    12. msc.setBasePackage("com.itheima.dao");
    13. return msc;
    14. }
    15. }

     SpringConfig配置类

    1. @Configuration
    2. @ComponentScan({"com.csdn.service"})
    3. @PropertySource("classpath:jdbc.properties")
    4. @Import({JdbcConfig.class,MyBatisConfig.class})
    5. @EnableTransactionManagement //开启Spring事务管理
    6. public class SpringConfig {
    7. }

    (3)Spring整合SpringMVC

    SpringMvcConfig配置类

    1. @Configuration
    2. @ComponentScan("com.csdn.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. }

    2、功能模块

    (1)数据层(BookDao)

    Book实体类

    1. public class Book {
    2. private Integer id;
    3. private String type;
    4. private String name;
    5. private String description;
    6. //需要补充getter、setter、toString()方法
    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 getAll();
    13. }

    (2)业务层开发(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 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 getAll() {
    21. return bookDao.getAll();
    22. }
    23. }

    (3)表现层开发(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 getAll() {
    24. return bookService.getAll();
    25. }
    26. }

    3、接口测试

    (1)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 all = bookService.getAll();
    14. System.out.println(all);
    15. }
    16. }

    (2)测试

    二、表现层数据封装

    1、整合中响应数据问题

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

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

    2、定义Result类封装响应结果

    (1)Result类封装响应结果

    1. public class Result {
    2. //描述统一格式中的数据
    3. private Object data;
    4. //描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功失败
    5. private Integer code;
    6. //描述统一格式中的消息,可选属性
    7. private String msg;
    8. public Result() {
    9. }
    10. public Result(Integer code,Object data) {
    11. this.data = data;
    12. this.code = code;
    13. }
    14. public Result(Integer code, Object data, String msg) {
    15. this.data = data;
    16. this.code = code;
    17. this.msg = msg;
    18. }
    19. //需要补充getter、setter、toString()方法
    20. }

    (2)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. }

    3、表现层数据封装返回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 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. }

  • 相关阅读:
    Spring源码深度解析(六):Spring事务传播机制详解
    Vue的路由
    Mysql__安装教程
    有什么好赚钱的项目可以做?这8个小项目不错,想赚钱的别错过!
    力扣刷题61-旋转链表
    CCF的计算机资格考试模拟题202305-1
    主键问题以及分布式 id
    java基于Springboot+vue的文体文具销售商城网站 elementui
    优思学院|看板方式与传统生产方式的对比
    一个案例体会Vue的优势
  • 原文地址:https://blog.csdn.net/weixin_43162044/article/details/127707845