SSM整合(配置类方式)

1. SSM整合

1.1 配置流程

步骤1: 创建maven的web项目
步骤2: 添加依赖:
 <dependencies>
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.15.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.15.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.15.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.15.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</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.23</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.1</version>
        </dependency>
    </dependencies>

步骤3: 创建包结构:

image-20221030112156080

步骤4:创建SpringConfig配置类
@Configuration //规定当前类为配置类
@ComponentScan("com.lty.service") //spring的配置类扫描service层
@PropertySource("classpath:db.properties") //加载properties文件
@Import({JdbcConfig.class,MybatisConfig.class}) //引入jdbc的配置类与mybatis的配置类
@EnableTransactionManagement //添加事务
public class SpringConfig {
}
步骤5:创建JdbcConfig配置类
public class JdbcConfig {
    @Value("${jdbc.driverClassName}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    //数据源
    @Bean
    public DataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    //数据源的事务
    @Bean
    public PlatformTransactionManager platformTransactionManager(DataSource dataSource){
        DataSourceTransactionManager ds = new DataSourceTransactionManager();
        ds.setDataSource(dataSource);
        return ds;
    }
}
步骤6:创建MybatisConfig配置类
public class MybatisConfig {
    //配置SqlSessionFactoryBean
    @Bean
    public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("com.lty.domain");
        return bean;
    }


    //配置MapperScannerConfigure   自动扫描dao(mapper)层的接口
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("com.lty.dao");
        return configurer;
    }
}

步骤7:创建db.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库?useSSl=false
jdbc.username=root
jdbc.password=root
步骤8:创建SpringMVCConfig配置类
@Configuration
@ComponentScan("com.lty.controller")
@EnableWebMvc
public class SpringMvcConfig {
}

步骤9:创建web项目入口配置类
public class ServletConfig  extends AbstractAnnotationConfigDispatcherServletInitializer {
    //加载spring的配置
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    //加载springMVC配置类
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    //设置MVC拦截规则
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    //设置post请求中文乱码

    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("utf-8");
        return new Filter[]{filter};
    }
}

SSM整合的环境搭建完成

1.2 功能模块开发

步骤1:创建数据库与表
create database ssm_db character set utf8;
use ssm_db;
create table tbl_book(
  id int primary key auto_increment,
  type varchar(20),
  name varchar(50),
  description varchar(255)
)

insert  into `tbl_book`(`id`,`type`,`name`,`description`) values (1,'计算机理论','Spring实战 第五版','Spring入门经典教程,深入理解Spring原理技术内幕'),(2,'计算机理论','Spring 5核心原理与30个类手写实践','十年沉淀之作,手写Spring精华思想'),(3,'计算机理论','Spring 5设计模式','深入Spring源码刨析Spring源码中蕴含的10大设计模式'),(4,'计算机理论','Spring MVC+Mybatis开发从入门到项目实战','全方位解析面向Web应用的轻量级框架,带你成为Spring MVC开发高手'),(5,'计算机理论','轻量级Java Web企业应用实战','源码级刨析Spring框架,适合已掌握Java基础的读者'),(6,'计算机理论','Java核心技术 卷Ⅰ 基础知识(原书第11版)','Core Java第11版,Jolt大奖获奖作品,针对Java SE9、10、11全面更新'),(7,'计算机理论','深入理解Java虚拟机','5个纬度全面刨析JVM,大厂面试知识点全覆盖'),(8,'计算机理论','Java编程思想(第4版)','Java学习必读经典,殿堂级著作!赢得了全球程序员的广泛赞誉'),(9,'计算机理论','零基础学Java(全彩版)','零基础自学编程的入门图书,由浅入深,详解Java语言的编程思想和核心技术'),(10,'市场营销','直播就这么做:主播高效沟通实战指南','李子柒、李佳奇、薇娅成长为网红的秘密都在书中'),(11,'市场营销','直播销讲实战一本通','和秋叶一起学系列网络营销书籍'),(12,'市场营销','直播带货:淘宝、天猫直播从新手到高手','一本教你如何玩转直播的书,10堂课轻松实现带货月入3W+');
步骤2:实体类:
public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;
    //getter...setter...toString省略
}
步骤3:dao接口:
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 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();
}
步骤4:service接口与实现类:
@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();
}
@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();
    }
}
  • bookDao在Service中注入的会提示一个红线提示,为什么呢?

    • BookDao是一个接口,没有实现类,接口是不能创建对象的,所以最终注入的应该是代理对象
    • 代理对象是由Spring的IOC容器来创建管理的,IOC容器又是在Web服务器启动的时候才会创建,IDEA在检测依赖关系的时候,没有找到适合的类注入,所以会提示错误提示,但是程序运行的时候,代理对象就会被创建,框架会使用DI进行注入,所以程序运行无影响。
  • 解决?

    运行时是正常的

步骤5:Controller类
@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<Book> getAll() {
        return bookService.getAll();
    }
}

1.3 单元测试

步骤1:新建测试类
步骤2:注入service类
编写测试方法
@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<Book> all = bookService.getAll();
        System.out.println(all);
    }

}

根据id查询:

image-20221030113832324

查询所有:

image-20221030113852312

2. 统一分装结果

将结果分装成一个对象,统一管理

image-20221030114357755

1. 表现层与前端数据传输协议实现

image-20221030114256228

2.2 结果分装

步骤1:创建Result类
@Data
@AllArgsConstructor
@NoArgsConstructor

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

    //构造方法是方便对象的创建
    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;
    }

步骤2:定义返回码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类中的常量可自行定义

步骤3:修改Controller类的返回值
//统一每一个控制器方法返回值
@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<Book> bookList = bookService.getAll();
        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookList != null ? "" : "数据查询失败,请重试!";
        return new Result(code,bookList,msg);
    }
}
步骤4:启动服务器测试

image-20221030131722600

3. 统一异常处理

当程序中出现异常时,程序就不能再执行下去

@GetMapping("/{id}")
public Result getById(@PathVariable Integer id) {
 //手动添加一个错误信息
 if(id==1){
     int i = 1/0;
 }
 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);
}

image-20221030131920765

3.1.异常种类及原因

异常原因
框架内部抛出异常是哦那个不合规
数据层抛出异常服务器故障
业务层抛出异常业务逻辑书写错误
表现层抛出异常数据收集、校验规则(如不匹配的数据类型)
工具类抛出异常工具类书写不够严谨

思考:

  1. 各个层级均出现异常,异常处理代码书写在哪一层?

    所有的异常均抛出到表现层进行处理

  2. 异常的种类很多,表现层如何将所有的异常都处理到呢?

    异常分类

  3. 表现层处理异常,每个方法中单独书写,代码书写量巨大且意义不强,如何解决?

    AOP

对于上面这些问题及解决方案,SpringMVC已经为我们提供了一套解决方案:

  • 异常处理器:

    • 集中的、统一的处理项目中出现的异常。

3.2.异常处理器的使用

环境准备:

image-20221030143459634

步骤1:创建异常处理器类
@RestControllerAdvice //标识当前类为rest风格对应的异常处理器
public class ProjectExceptionAdvice {
    //除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
    @ExceptionHandler(Exception.class) //设置当前处理器对应的异常类型
    public void doException(Exception ex){
      	System.out.println("嘿嘿,异常你哪里跑!")
    }
}
步骤2:程序抛出异常
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id) {
  	int i = 1/0;
    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);
}
步骤3:运行:

image-20221030144014116

异常处理器类返回结果给前端:
@RestControllerAdvice //标识当前类为rest风格对应的异常处理器
public class ProjectExceptionAdvice {
    //除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
    @ExceptionHandler(Exception.class) //设置当前处理器对应的异常类型
    public Result doException(Exception ex){
      	System.out.println("嘿嘿,异常你哪里跑!")
        retrun new Result(666,null,"嘿嘿,异常你哪里跑!")
    }
}
  • 此处根据result类的构造方法创建

image-20221030144702384

image-20221030144818841

说明: @RestControllerAdvice注解自带@ResponseBody注解与@Component注解,具备对应的功能

3.3 项目异常处理方案

因为异常的种类有很多,如果每一个异常都对应一个@ExceptionHandler,那得写多少个方法来处理各自的异常,所以我们在处理异常之前,需要对异常进行一个分类:

  • 业务类(BusinessException)
    • 规范的用户行为产生的异常(如:年龄框输入了字符串)
    • 不规范的用户行为操作(如:故意传递错误的信息)
  • 系统异常(SystemException)
    • 如数据库、服务器宕机
  • 其他异常(Exception)
    • 编程人员未预期到的异常

3.3.2 异常解决方案

业务异常提醒用户规范操作密码格式输入
系统异常发送固定消息给用户,安抚用户/发送给运维人员/记录日志/系统繁忙,请稍后再试/系统维护中
其他日志

3.3.3 异常解决方案的具体实现

思路:

  1. 自定义异常,完成BusinessException与SystemException的定义
  2. 将其他的异常包装成自定义异常类型
  3. 在异常处理器中对不同的异常进行处理
步骤1: 自定义异常类
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;
    }
}

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;
    }
}

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;
    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;
}

说明:

  • 让自定义异常类继承RuntimeException的好处是,后期在抛出这两个异常的时候,就不用在try…catch…或throws了
  • 自定义异常类中添加code属性的原因是为了更好的区分异常是来自哪个业务的
步骤2:将其他异常包装成自定义异常
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);
}
步骤4:处理器中处理自定义异常
//创建异常处理器
@RestControllerAdvice
public class ProjectExceptionAdvice {


    @ExceptionHandler(SystemException.class)
    //系统异常
    public Result doSystemException(SystemException ex) {
        //记录日志
        //发消息给运维人员
        //发送邮件给开发人员
        return new Result(ex.getCode(), (Object) null, ex.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    //系统异常
    public Result doBusinessException(BusinessException ex) {
        return new Result(ex.getCode(), (Object) null, ex.getMessage());
    }

    //保留Exception类型的异常处理
    @ExceptionHandler(Exception.class)
    public Result HandleException(Exception ex) {
        //记录日志
        //发消息给运维人员
        //发送邮件给开发人员

        return new Result(Code.SYSTEM_UNKNOW_ERR, (Object) null, "系统繁忙,请稍后再试!");
    }

}
步骤4:运行

根据id查询:

image-20221030152018713

image-20221030152100242

小结:

以后项目中的异常处理方式为:

image-20221030152153356

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值