我们在前面已经学习了Maven基本入门,Spring,SpringMVC,MyBatis三件套
现在我们来通过一些简单的案例,将我们最常用的开发三件套整合起来,进行一次完整的项目展示
温馨提示:在阅读本篇文章前,请学习Maven,Spring,SpringMVC,MyBatis等内容
SSM整合案例
接下来我们通过各个部分的准备与介绍进行一次SSM项目的内容整合
案例介绍阶段
案例介绍:
- 我们希望通过网页进行操作数据库内容 
数据库目前资料:

案例准备阶段
- 创建工程 
我们采用Maven项目的maven-webapp创建项目

- 补充相关文档以及设置文档构造名称 

案例书写阶段
- 数据库准备阶段 
CREATE DATABASE SMM; USE SMM; -- ---------------------------- -- Table structure for tbl_book -- ---------------------------- DROP TABLE IF EXISTS `tbl_book`; CREATE TABLE `tbl_book` ( `id` int(11) NOT NULL AUTO_INCREMENT, `type` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `description` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of tbl_book -- ---------------------------- INSERT INTO `tbl_book` VALUES (1, '计算机理论', 'Spring实战 第5版', 'Spring入门经典教程,深入理解Spring原理技术内幕'); INSERT INTO `tbl_book` VALUES (2, '计算机理论', 'Spring 5核心原理与30个类手写实战', '十年沉淀之作,手写Spring精华思想'); INSERT INTO `tbl_book` VALUES (3, '计算机理论', 'Spring 5 设计模式', '深入Spring源码剖析Spring源码中蕴含的10大设计模式'); INSERT INTO `tbl_book` VALUES (4, '计算机理论', 'Spring MVC+MyBatis开发从入门到项目实战', '全方位解析面向Web应用的轻量级框架,带你成为Spring MVC开发高手'); INSERT INTO `tbl_book` VALUES (5, '计算机理论', '轻量级Java Web企业应用实战', '源码级剖析Spring框架,适合已掌握Java基础的读者'); INSERT INTO `tbl_book` VALUES (6, '计算机理论', 'Java核心技术 卷I 基础知识(原书第11版)', 'Core Java 第11版,Jolt大奖获奖作品,针对Java SE9、10、11全面更新'); INSERT INTO `tbl_book` VALUES (7, '计算机理论', '深入理解Java虚拟机', '5个维度全面剖析JVM,大厂面试知识点全覆盖'); INSERT INTO `tbl_book` VALUES (8, '计算机理论', 'Java编程思想(第4版)', 'Java学习必读经典,殿堂级著作!赢得了全球程序员的广泛赞誉'); INSERT INTO `tbl_book` VALUES (9, '计算机理论', '零基础学Java(全彩版)', '零基础自学编程的入门图书,由浅入深,详解Java语言的编程思想和核心技术'); INSERT INTO `tbl_book` VALUES (10, '市场营销', '直播就该这么做:主播高效沟通实战指南', '李子柒、李佳琦、薇娅成长为网红的秘密都在书中'); INSERT INTO `tbl_book` VALUES (11, '市场营销', '直播销讲实战一本通', '和秋叶一起学系列网络营销书籍'); INSERT INTO `tbl_book` VALUES (12, '市场营销', '直播带货:淘宝、天猫直播从新手到高手', '一本教你如何玩转直播的书,10堂课轻松实现带货月入3W+');
- 导入相关坐标 
<?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>com.itheima</groupId> <artifactId>springmvc_08_ssm</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.10.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.16</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.1</version> <configuration> <port>80</port> <path>/</path> </configuration> </plugin> </plugins> </build> </project>
- jdbc配置资文档准备 
// jdbc.properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm jdbc.username=root jdbc.password=123456
- SpringConfig配置类 
// SpringConfig
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
// Spring配置类
@Configuration
// 扫描包
@ComponentScan({"com.itheima.service"})
// 资源载入
@PropertySource("classpath:jdbc.properties")
// 与MyBatis链接
@Import({JdbcConfig.class,MyBatisConfig.class})
// 开启事务平台
@EnableTransactionManagement
public class SpringConfig {
}- MyBatisConfig配置类 
// JdbcConfig
package com.itheima.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
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
    // 配置资源(这里采用的是DruidDataSource)
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
    // 设置为Bean
    // 配置事务平台(这里采用的是DataSourceTransactionManager)
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        DataSourceTransactionManager ds = new DataSourceTransactionManager();
        ds.setDataSource(dataSource);
        return ds;
    }
}// MyBatisConfig
package com.itheima.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MyBatisConfig {
    // 设置为Bean
    // 创建工厂SqlSessionFactory,用于实现数据库交互
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.itheima.domain");
        return factoryBean;
    }
    // 设置为Bean
    // 创建映射,并定义映射地址,采用MapperScannerConfigurer
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.itheima.dao");
        return msc;
    }
}- SpringMvcConfig配置类 
// SpringMvcConfig
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
// Spring配置类
@Configuration
// 扫描包
@ComponentScan("com.itheima.controller")
// 万能工具注解
@EnableWebMvc
public class SpringMvcConfig {
}// ServletConfig
package com.itheima.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
// 注意:继承于AbstractAnnotationConfigDispatcherServletInitializer
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    // 设置SpringConfig
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }
    // 设置SpringMvcConfig
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }
    // 设置路径锁定"/"即可
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}- 数据库对应实体类创建 
// Book
package com.itheima.domain;
public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;
    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", type='" + type + '\'' +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}- 数据层代码 
// BookDao
package com.itheima.dao;
import com.itheima.domain.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface BookDao {
    // 采用Mapper代理开发
    // 采用#{}匹配参数
    @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
    public void save(Book book);
    @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
    public void update(Book book);
    @Delete("delete from tbl_book where id = #{id}")
    public void delete(Integer id);
    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);
    @Select("select * from tbl_book")
    public List<Book> getAll();
}- 业务层代码 
// BookService
package com.itheima.service;
import com.itheima.domain.Book;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
// 给出事务开启标志
@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<Book> getAll();
}// BookServiceImpl
package com.itheima.service.impl;
import com.itheima.dao.BookDao;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
// 标记为Bean
@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<Book> getAll() {
        return bookDao.getAll();
    }
}- 服务层代码 
package com.itheima.controller;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
// 标记为Bean
// 采用REST书写方式
@RestController
// 设置总体路径前缀
@RequestMapping("/books")
public class BookController {
	// 自动装配
    @Autowired
    private BookService bookService;
    // 新添采用POST请求
    // 数据位于请求体,采用@RequestBody
    @PostMapping
    public boolean save(@RequestBody Book book) {
        return bookService.save(book);
    }
    // 更新采用PUT请求
    // 数据位于请求体,采用@RequestBody
    @PutMapping
    public boolean update(@RequestBody Book book) {
        return bookService.update(book);
    }
    // 删除采用DELETE请求
    // 数据位于请求路径,采用@PathVariable,并在路径采用{}表示
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return bookService.delete(id);
    }
    // 访问采用GET请求
    // 数据位于请求路径,采用@PathVariable,并在路径采用{}表示
    @GetMapping("/{id}")
    public Book getById(@PathVariable Integer id) {
        return bookService.getById(id);
    }
    // 访问采用GET请求
    @GetMapping
    public List<Book> getAll() {
        return bookService.getAll();
    }
}案例测试阶段
- Java内部代码测试 
// 测试均实现于test文件夹下
package com.itheima.service;
import com.itheima.config.SpringConfig;
import com.itheima.domain.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
// 测试采用的junit
@RunWith(SpringJUnit4ClassRunner.class)
// 测试采用的配置文件
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {
    // 自动装配
    @Autowired
    private BookService bookService;
    // 查询id=1的值
    @Test
    public void testGetById(){
        Book book = bookService.getById(1);
        System.out.println(book);
    }
    // 查询所有数据
    @Test
    public void testGetAll(){
        List<Book> all = bookService.getAll();
        System.out.println(all);
    }
}- Postman测试 
我们需要采用网页进行测试是否满足需求,下面仅列出简单示例:

案例总结阶段
以上部分就是根据我们之前所学内容所整合出来的整体框架,我们已经基本做成了一个简单的服务器
SSM表现层数据封装
我们在上一小节已经完成了一个基本项目的开发
但是我们会注意到我们服务层的返回数据类型不尽相同:
package com.itheima.controller;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;
    // 我们会注意到我们返回的数据有时为boolean,有时为Book,有时为List<Book>
    @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<Book> getAll() {
        return bookService.getAll();
    }
}我们需要注意的是:
- 项目并非我们一个人开发,我们在实际开发中大部分前后端是分离的,也就是说我们返回的数据是返回给前端进行处理的 
- 但前端并不熟悉后端的代码,所以我们如果毫无忌惮的传递没有任何说明的数据,前端是无法把它做成页面展现出来的 
- 所以前后端通常需要一种规范来设计返回类型,让前端能够明白后端所传递的数据,我们通常把他称为表现层数据封装 
表现层数据封装概念
为了保障前后端沟通无障碍,在项目开始时,前后端会进行一次沟通来确定后端传递数据的规范,我们通常把它称为表现层数据封装
我们通常采用一个实现类来规定数据封装格式:
public class Result{
    // 这里我们假设给出三种数据来进行前后端沟通
    /*
    data:数据内容
    code:状态码
    msg:相关信息
    */
	private Object data;
    private Integer code;
    private String msg;
}这里的data数据就是取自表现层数据,code是双方规定的状态码,msg是用于提供相关附属信息
Result类中的字段不是固定的,可以根据需求自行删减
注意需要提供若干个构造方法,方便操作
表现层数据封装操作
接下里我们以第一阶段案例给出相关修改案例:
- 设计Code状态码 
package com.itheima.controller;
//状态码
//通常是双方协议或公司规定
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;
}- 设计Result返回数据规范 
package com.itheima.controller;
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;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}- 服务层返回数据更替 
package com.itheima.controller;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
//统一每一个控制器方法返回值
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;
    // 我们按照Result的构造方法以及实际需求提供返回值
    // 我们可以根据三目运算符来直接输出其结果
    @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<Book> bookList = bookService.getAll();
        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookList != null ? "" : "数据查询失败,请重试!";
        return new Result(code,bookList,msg);
    }
}异常处理器
我们的程序可能或者说必然会出现一些漏洞,有些可能是人为的,有些可能是我们代码的问题
所以为了处理这些异常,首先我们需要把异常出现的常见位置与原因进行分类:
- 框架内部抛出的异常:因使用不合规导致 
- 数据层抛出的异常:因外部服务器故障导致(例如:服务器访问超时) 
- 业务层抛出的异常:因业务逻辑书写错误导致(例如:遍历业务书写操作,导致索引异常等) 
- 表现层抛出的异常:因数据收集,校验等规则导致(例如:不匹配的数据类型间导致异常) 
- 工具类抛出的异常:因工具类书写不严谨不够健全导致(例如:必要释放的连接长期未释放) 
那么我们来思考两个问题来确定异常处理器的书写方法和位置:
- 在上述我们可以看到各个层级都会出现问题,那么我们的异常处理器应该写在哪一层? 
- 所有的异常均向上抛出至表现层进行处理 
- 表现层处理异常,每个方法单独书写,代码书写量巨大且意义不大,该怎么处理? 
- 采用AOP思想 
编写基本异常处理器
我们常常会集中的,统一的处理项目中出现的异常
前面我们说过需要在表现层统一处理异常,所以我们选择在表现层书写异常处理器:
package com.itheima.controller;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//@RestControllerAdvice用于标识当前类为REST风格对应的异常处理器
@RestControllerAdvice
public class ProjectExceptionAdvice {
    // @ExceptionHandler用于设置当前处理器类对应的异常类型
    // 这里处理的是Exception.class,属于最大的异常处理
    @ExceptionHandler(Exception.class)
    public Result doOtherException(Exception ex){
        // Code.SYSTEM_UNKNOW_ERR是在Code状态码文件中统一设置的,null是返回值,后面属于附加内容用于安抚用户
        return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");
    }
}
/*
名称:@RestControllerAdvice
类型:类注解
位置:Rest风格开发的控制器增强类定义上方
作用:为Rest风格开发的控制器类做增强
说明:此注解自带@ResponseBody注解与@Component注解,具备对应的功能
名称:@ExceptionHandler
类型:方法注解
位置:专用于异常处理的控制器方法上方
作用:设置指定异常的处理方案,功能等同于控制器方法,出现异常后终止原始控制器操作,并转入该方法进行执行
说明:此类方法可以根据处理的异常不同,制作多个方法分别处理对应的异常
*/编写项目异常处理
我们的项目异常处理通常不会直接对最大异常处理
因为我们的项目通常会出现很多种类型的异常,例如用户操作错误产生的异常,编程人员未预期到的异常
我们进行一个简单的分类:
- 业务异常(BusinessException) 
- 规范的用户行为产生的异常 
- 不规范的用户行为操作产生的异常 
- 系统异常(SystemException) 
- 项目运行过程中可预计且无法避免的异常 
- 其他异常(Exception) 
- 编程人员未预期到的异常 
对于不同的异常,我们采用不同的应对方法,我们下面做出简单的处理:
- Code状态码增加 
package com.itheima.controller;
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;
    public static final Integer SYSTEM_ERR = 50001;
    public static final Integer SYSTEM_TIMEOUT_ERR = 50002;
    public static final Integer SYSTEM_UNKNOW_ERR = 59999;
    public static final Integer BUSINESS_ERR = 60002;
}- 书写自定义异常处理器 
// SystemException
package com.itheima.exception;
//自定义异常处理器,用于封装异常信息,对异常进行分类,需要继承RuntimeException
public class SystemException extends RuntimeException{
    private Integer code;
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public SystemException(Integer code, String message) {
        super(message);
        this.code = code;
    }
    public SystemException(Integer code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }
}// BusinessException
package com.itheima.exception;
//自定义异常处理器,用于封装异常信息,对异常进行分类,需要继承RuntimeException
public class BusinessException extends RuntimeException{
    private Integer code;
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public BusinessException(Integer code, String message) {
        super(message);
        this.code = code;
    }
    public BusinessException(Integer code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }
}- 这里选择在业务层抛出异常 
package com.itheima.service.impl;
import com.itheima.controller.Code;
import com.itheima.dao.BookDao;
import com.itheima.domain.Book;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@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) {
        //模拟业务异常,包装成自定义异常
        if(id == 1){
            throw new BusinessException(Code.BUSINESS_ERR,"请不要使用你的技术挑战我的耐性!");
        }
        //模拟系统异常,将可能出现的异常进行包装,转换成自定义异常
        try{
            int i = 1/0;
        }catch (Exception e){
            throw new SystemException(Code.SYSTEM_TIMEOUT_ERR,"服务器访问超时,请重试!",e);
        }
        return bookDao.getById(id);
    }
    public List<Book> getAll() {
        return bookDao.getAll();
    }
}- 表现层异常处理器增加 
package com.itheima.controller;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//@RestControllerAdvice用于标识当前类为REST风格对应的异常处理器
@RestControllerAdvice
public class ProjectExceptionAdvice {
    //@ExceptionHandler用于设置当前处理器类对应的异常类型
    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException ex){
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,ex对象发送给开发人员
        return new Result(ex.getCode(),null,ex.getMessage());
    }
    @ExceptionHandler(BusinessException.class)
    public Result doBusinessException(BusinessException ex){
        return new Result(ex.getCode(),null,ex.getMessage());
    }
    //除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
    @ExceptionHandler(Exception.class)
    public Result doOtherException(Exception ex){
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,ex对象发送给开发人员
        return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");
    }
}前后端协议联调
在定义了前后端的协议规范并完成了后端开发后,我们还需要设计前端的开发
关于前端开发并不是我们的重点,所以下面只作简单介绍
拦截器设置
首先我们需要注意我们的SpringMVC的拦截路径设置为全部路径:
// ServletContainersInitConfig
package com.itheima.config;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    protected Class<?>[] getRootConfigClasses() {
        return new Class[0];
    }
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }
    protected String[] getServletMappings() {
        // 系统会将全部路径下的请求都交付给SpringMVC处理
        return new String[]{"/"};
    }
    //乱码处理
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        return new Filter[]{filter};
    }
}所以当我们查询主页网页时,会被SpringMVC接收并且要求返回一个相关的服务层方法,很明显这是错误的
所以我们需要设置一个拦截器用来放行一些网页相关的资源,使用户访问时,直接将相关页面资源反馈回去:
// 我们选择在Config文件夹下创建SpringMvcSupport继承WebMvcConfigurationSupport作为SpringMVC的工具类
package com.itheima.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
// 需要继承WebMvcConfigurationSupport用作工具类
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
    // 继承addResourceHandlers方法,进行放行操作
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 利用参数registry,addResourceHandler后跟参数路径,addResourceLocations后跟访问页面
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
    }
}同时记得在SpringMvcConfig中扫描相关类:
// SpringMvcConfig
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@ComponentScan({"com.itheima.controller","com.itheima.config"})
@EnableWebMvc
public class SpringMvcConfig {
}前端操作简单讲解
当我们设置好拦截器后,我们就可以通过页面访问进入到html主页:
我们希望可以实现查询,创建,修改,删除等操作
在下述操作中我们采用html和Ajax两门技术实现上述操作:
- 首先我们需要在Dao数据层进行一些返回值的修改: 
package com.itheima.dao;
import com.itheima.domain.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface BookDao {
    // 我们采用int作为返回值,当作数据库操作的行数返回值,用来判断是否操作成功
    @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<Book> getAll();
}- 我们对html页面进行操作: 
<!DOCTYPE html> <html> <head> <!-- 页面meta --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>SpringMVC案例</title> <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport"> <!-- 引入样式 --> <link rel="stylesheet" href="../plugins/elementui/index.css"> <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" href="../css/style.css"> </head> <body class="hold-transition"> <div id="app"> <div class="content-header"> <h1>图书管理</h1> </div> <div class="app-container"> <div class="box"> <div class="filter-container"> <el-input placeholder="图书名称" v-model="pagination.queryString" style="width: 200px;" class="filter-item"></el-input> <el-button @click="getAll()" class="dalfBut">查询</el-button> <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button> </div> <el-table size="small" current-row-key="id"&nb
标签: # SSM

留言评论