IT俱乐部 Java SpringMVC整合SSM实现表现层数据封装详解

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

SSM整合配置

SSM整合流程

1.创建工程

2.SSM整合

Spring

  • SpringConfig

MyBatis

  • MybatisConfig
  • JdbcConfig
  • jdbc.properties

SpringMVC

  • ServletConfig
  • SpringMvcConfig

3.功能模块

表与实体类

dao(接口+自动代理)

service(接口+实现类)

  • 业务层接口测试(整合JUnit)

controller

  • 表现层接口测试(PostMan)

SSM整合配置

创建工程,添加依赖和插件

org.springframeworkspring-webmvc5.2.10.RELEASEorg.springframeworkspring-jdbc5.2.10.RELEASEorg.springframeworkspring-test5.2.10.RELEASEorg.mybatismybatis3.5.6org.mybatismybatis-spring1.3.0mysqlmysql-connector-java5.1.47com.alibabadruid1.1.16junitjunit4.12testjavax.servletjavax.servlet-api3.1.0providedcom.fasterxml.jackson.corejackson-databind2.9.0org.projectlomboklombok1.18.24org.apache.tomcat.maventomcat7-maven-plugin2.180/

Spring整合Mybatis

创建数据库和表

-- 创建db5数据库
CREATE DATABASE IF NOT EXISTS db5 CHARACTER SET utf8;
-- 使用db5数据库
USE db5;
-- 创建tbl_book表
CREATE TABLE tbl_book(
    id INT PRIMARY KEY AUTO_INCREMENT, -- 图书编号
    TYPE VARCHAR(100), -- 图书类型
    NAME VARCHAR(100), -- 图书名称
    description VARCHAR(100) -- 图书描述
);
-- 添加初始化数据
INSERT INTO tbl_book VALUES(NULL,'图书类型一','图书名称一','图书描述一');
INSERT INTO tbl_book VALUES(NULL,'图书类型二','图书名称二','图书描述二');
INSERT INTO tbl_book VALUES(NULL,'图书类型三','图书名称三','图书描述三');
INSERT INTO tbl_book VALUES(NULL,'图书类型四','图书名称四','图书描述四');
INSERT INTO tbl_book VALUES(NULL,'图书类型五','图书名称五','图书描述五');
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配置类

public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    //配置连接池
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
    //Spring事务管理需要的平台事务管理器对象
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        DataSourceTransactionManager ds = new DataSourceTransactionManager();
        ds.setDataSource(dataSource);
        return ds;
    }
}

MybatisConfig配置类

public class MyBatisConfig {
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.moming.domain");
        return factoryBean;
    }
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.moming.dao");
        return msc;
    }
}

SpringConfig配置类

@Configuration
@ComponentScan({"com.moming.service"})
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MyBatisConfig.class})
@EnableTransactionManagement //开启Spring事务管理
public class SpringConfig {
}

Spring整合SpringMVC

SpringMvcConfig配置类

@Configuration
@ComponentScan("com.moming.controller")
@EnableWebMvc
public class SpringMvcConfig {
}

ServletConfig配置类,加载SpringMvcConfig和SpringConfig配置类

public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    protected Class>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }
    protected Class>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
    //乱码处理
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        return new Filter[]{filter};
    }
}

功能模块开发

数据层开发(BookDao)

Book实体类

@Data
public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;
}

BookDao接口

public interface BookDao {
    //@Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
    @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
    public int save(Book book);  //返回值表示影响的行数
    @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
    public int update(Book book);
    @Delete("delete from tbl_book where id = #{id}")
    public int delete(Integer id);
    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);
    @Select("select * from tbl_book")
    public List getAll();
}

业务层开发(BookService/BookServiceImpl)

BookService接口

@Transactional //表示所有方法进行事务管理
public interface BookService {
    /**
     * 保存
     * @param book
     * @return
     */
    public boolean save(Book book);
    /**
     * 修改
     * @param book
     * @return
     */
    public boolean update(Book book);
    /**
     * 根据id删除
     * @param id
     * @return
     */
    public boolean delete(Integer id);
    /**
     * 按id查询
     * @param id
     * @return
     */
    public Book getById(Integer id);
    /**
     * 查询全部
     * @return
     */
    public List getAll();
}

BookServiceImpl实现类

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;
    public boolean save(Book book) {
        bookDao.save(book);
        return true;
    }
    public boolean update(Book book) {
        bookDao.update(book);
        return true;
    }
    public boolean delete(Integer id) {
        bookDao.delete(id);
        return true;
    }
    public Book getById(Integer id) {
        return bookDao.getById(id);
    }
    public List getAll() {
        return bookDao.getAll();
    }
}

表现层开发(BookController)

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;
    @PostMapping
    public boolean save(@RequestBody Book book) {
        return bookService.save(book);
    }
    @PutMapping
    public boolean update(@RequestBody Book book) {
        return bookService.update(book);
    }
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return bookService.delete(id);
    }
    @GetMapping("/{id}")
    public Book getById(@PathVariable Integer id) {
        return bookService.getById(id);
    }
    @GetMapping
    public List getAll() {
        return bookService.getAll();
    }
}

接口测试

Spring整合Junit测试业务层方法

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {
    @Autowired
    private BookService bookService;
    @Test
    public void testGetById(){
        Book book = bookService.getById(1);
        System.out.println(book);
    }
    @Test
    public void testGetAll(){
        List all = bookService.getAll();
        System.out.println(all);
    }
}

postman测试表现层接口

测试保存图书

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

表现层响应数据的问题

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

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

定义Result类封装响应结果

controller/Result类封装响应结果

@Data
public class Result {
    //描述统一格式中的数据
    private Object data;
    //描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功失败
    private Integer code;
    //描述统一格式中的消息,可选属性
    private String msg;
    public Result() {
    }
    public Result(Integer code,Object data) {
        this.data = data;
        this.code = code;
    }
    public Result(Integer code, Object data, String msg) {
        this.data = data;
        this.code = code;
        this.msg = msg;
    }
}

注意事项:Result类中的字段并不是固定的,可以根据需要自行增减

controller/Code类封装响应码

//状态码
public class Code {
    public static final Integer SAVE_OK = 20011;
    public static final Integer DELETE_OK = 20021;
    public static final Integer UPDATE_OK = 20031;
    public static final Integer GET_OK = 20041;
    public static final Integer SAVE_ERR = 20010;
    public static final Integer DELETE_ERR = 20020;
    public static final Integer UPDATE_ERR = 20030;
    public static final Integer GET_ERR = 20040;
}

注意事项:Code类的常量设计也不是固定的,可以根据需要自行增减,例如将查询再进行细分为GET_OK,GET_ALL_OK,GET_PAGE_OK

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

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;
    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
    }
    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
    }
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
        String msg = book != null ? "" : "数据查询失败,请重试!";
        return new Result(code,book,msg);
    }
    @GetMapping
    public Result getAll() {
        List bookList = bookService.getAll();
        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookList != null ? "" : "数据查询失败,请重试!";
        return new Result(code,bookList,msg);
    }
}

Postman测试

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

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/6862.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部