美文网首页
22.SSM整合

22.SSM整合

作者: 星野君 | 来源:发表于2022-05-04 14:45 被阅读0次

    一、整合流程

    1. 创建工程
    2. SSM整合
    • Spring
      • SpringConfig
    • MyBatis
      • MybatisConfig
      • JdbcConfig
      • jdbc.properties
    • SpringMVC
      • ServletConfig
      • SpringMvcConfig

    二、快速构建

    1. 导入坐标,引入tomcat
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.3.19</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.3.18</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>5.3.18</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.5</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.6</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.32</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.12</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.0.1</version>
                <scope>provided</scope>
            </dependency>
            <!--json转换-->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.9.0</version>
            </dependency>
        </dependencies>
        <!--tomcat插件-->
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <configuration>
                        <port>80</port>
                        <path>/</path>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    1. 创建配置文件
    • 结构图


      image.png
    • SpringConfig
    package com.ylf.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;
    
    @Configuration
    @ComponentScan({"com.ylf.service"})
    @PropertySource("jdbc.properties")
    @Import({JdbcConfig.class, MyBatisConfig.class})
    // 开启事务注解
    @EnableTransactionManagement
    public class SpringConfig {
    }
    
    
    • JdbcConfig
    package com.ylf.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    
    import javax.sql.DataSource;
    
    public class JdbcConfig {
      @Value("${jdbc.driver}")
      private String driver;
      @Value("${jdbc.url}")
      private String url;
      @Value("${jdbc.name}")
      private String name;
      @Value("${jdbc.password}")
      private String password;
    
      @Bean
      public DataSource dataSource(){
        final DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(name);
        dataSource.setPassword(password);
        return dataSource;
      }
    }
    
      @Bean
      public PlatformTransactionManager transactionManager(DataSource dataSource) {
        DataSourceTransactionManager ds = new DataSourceTransactionManager();
        ds.setDataSource(dataSource);
        return ds;
      }
    
    
    • MyBatisConfig
    package com.ylf.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
      public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.ylf.pojo");
        return factoryBean;
      }
    
      @Bean
      public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.ylf.dao");
        return msc;
      }
    }
    
    
    • jdbc.properties
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/db02
    jdbc.name=root
    jdbc.password=123
    
    • SpringMvcConfig
    package com.ylf.config;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    
    @Configuration
    @ComponentScan("com.ylf.controller")
    @EnableWebMvc
    public class SpringMvcConfig {}
    
    
    • ServletConfig
    package com.ylf.config;
    
    import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
    
    public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
      @Override
      protected Class<?>[] getRootConfigClasses() {
        return new Class[] {SpringConfig.class};
      }
    
      @Override
      protected Class<?>[] getServletConfigClasses() {
        return new Class[] {SpringMvcConfig.class};
      }
    
      @Override
      protected String[] getServletMappings() {
        return new String[] {"/"};
      }
    }
    
    
    1. 定义返回格式
    • 在controller里创建Result类
    package com.ylf.controller;
    
    public class Result {
      private Object data;
      private Integer code;
      private String message;
    
      public Result() {}
    
      public Result(Integer code, Object data) {
        this.data = data;
        this.code = code;
      }
    
      public Result(Integer code, Object data, String message) {
        this.data = data;
        this.code = code;
        this.message = message;
      }
    
      public String getMessage() {
        return message;
      }
    
      public void setMessage(String message) {
        this.message = message;
      }
    
      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;
      }
    }
    
    
    • 定义Code类型
    package com.ylf.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;
    }
    
    
    • controller
    package com.ylf.controller;
    
    import com.ylf.pojo.Student;
    import com.ylf.service.StudentService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    @RestController
    @RequestMapping("/students")
    public class StudentController {
      @Autowired private StudentService studentService;
    
      @PostMapping
      public Result save(@RequestBody Student student) {
        Boolean flag = studentService.save(student);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
      }
    
      @PutMapping
      public Result update(@RequestBody Student student) {
        Boolean flag = studentService.update(student);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
      }
    
      @DeleteMapping("/{id}")
      public Result delete(@PathVariable Integer id) {
        Boolean flag = studentService.delete(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
      }
    
      @GetMapping("/{id}")
      public Result findById(@PathVariable Integer id) {
        final Student student = studentService.findById(id);
        return new Result(
            student != null ? Code.GET_OK : Code.GET_ERR, student, student != null ? "请求成功" : "数据请求失败");
      }
    
      @GetMapping
      public Result findAll() {
        final List<Student> student = studentService.findAll();
        return new Result(
            student != null ? Code.GET_OK : Code.GET_ERR, student, student != null ? "请求成功" : "数据请求失败");
      }
    }
    
    

    四、异常处理

    1. 在controller里创建ProjectExceptionAdvice类。声明这个类用来做异常处理
    package com.ylf.controller;
    
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RestControllerAdvice;
    
    @RestControllerAdvice
    public class ProjectExceptionAdvice {
      // 统一处理所有异常
      @ExceptionHandler(Exception.class)
      public Result doException(Exception ex) {
        return new Result(500, null, "发生异常");
      }
    }
    

    记得加包扫描。@SpringBootApplication和ComponentScan一起用的话ComponentScan会覆盖掉SpringBootApplication

    @ComponentScan("com.ylf.controller")
    
    1. 创建自定义异常类
      BusinessException
    package com.ylf.exception;
    
    public class BusinessException extends RuntimeException {
      private Integer code;
    
      public Integer getCode() {
        return code;
      }
    
      public void setCode(Integer code) {
        this.code = code;
      }
    
      public BusinessException(String message, Integer code) {
        super(message);
        this.code = code;
      }
    
      public BusinessException(String message, Throwable cause, Integer code) {
        super(message, cause);
        this.code = code;
      }
    }
    
    

    SystemException

    package com.ylf.exception;
    
    public class SystemException extends RuntimeException {
      private Integer code;
    
      public Integer getCode() {
        return code;
      }
    
      public void setCode(Integer code) {
        this.code = code;
      }
    
      public SystemException(String message, Integer code) {
        super(message);
        this.code = code;
      }
    
      public SystemException(String message, Throwable cause, Integer code) {
        super(message, cause);
        this.code = code;
      }
    }
    
    
    1. 定义code异常类型
    package com.ylf.controller;
    public class Code {
    
      public static final Integer SYSTEM_ERR = 50001;
      public static final Integer BUSINESS_ERR = 50002;
      public static final Integer SYSTEM_UNKNOWN_ERR = 50003;
    }
    
    1. 在controller里可能会出现异常的地方抛出自定义异常
      @GetMapping("/{id}")
      public Result findById(@PathVariable Integer id) {
        try {
          int i = 1 / 0;
        } catch (Exception e) {
          throw new BusinessException("出现异常", e, Code.BUSINESS_ERR);
        }
        final Student student = studentService.findById(id);
        return new Result(
            student != null ? Code.GET_OK : Code.GET_ERR, student, student != null ? "请求成功" : "数据请求失败");
      }
    
    1. 拦截并处理异常
    package com.ylf.controller;
    
    import com.ylf.exception.BusinessException;
    import com.ylf.exception.SystemException;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RestControllerAdvice;
    
    @RestControllerAdvice
    public class ProjectExceptionAdvice {
      @ExceptionHandler(Exception.class)
      public Result doException(Exception ex) {
        // 1. 记录日志
        // 2. 发送ex对象邮件给开发人员
        return new Result(Code.SYSTEM_UNKNOWN_ERR, null, "系统繁忙");
      }
    
      @ExceptionHandler(SystemException.class)
      public Result doSystemException(SystemException ex) {
        // 1. 记录日志
        // 2. 发送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());
      }
    }
    
    

    相关文章

      网友评论

          本文标题:22.SSM整合

          本文链接:https://www.haomeiwen.com/subject/gathyrtx.html