当前位置: 首页 > news >正文

SSM整合

 

1.1ssm
  1. 首先导入jar包

     <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.13.1</version>
          <scope>test</scope>
        </dependency>
        <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.10</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>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>
    ​
  2. 创建jdbc.properties文件

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssm_db
    jdbc.username=root
    jdbc.password=root
  3. 创建配置文件SpringConfig,SpringMvcConfig

    //springConfig
    @Configuration
    @ComponentScan({"com.scidag.service","com.scidag.controller"})
    @PropertySource("classpath:jdbc.properties")
    @Import({JdbcConfig.class,MybatisConfig.class})
    @EnableTransactionManagement
    public class SpringConfig {
    }
    ​
    //SpringMvcConfig
    @Configuration
    @ComponentScan("com.scidag.controller")
    @EnableWebMvc
    public class SpringMvcConfig {
    ​
    }
    ​
  4. 创建JdbcConfig,MybatisConfig

    //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;
        }
        @Bean
        public PlatformTransactionManager transactionManager(DataSource dataSource){//设置spring事务
            DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
            dataSourceTransactionManager.setDataSource(dataSource);
            return  dataSourceTransactionManager;
        }
    }
    //MybatisConfig
    public class MybatisConfig {
        @Bean
        public SqlSessionFactoryBean sqlSessionFactoryBean( DataSource dataSource){
            SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setTypeAliasesPackage("com.scidag.pojo");
            sqlSessionFactoryBean.setDataSource(dataSource);
            return  sqlSessionFactoryBean;
        }
        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer(){
            MapperScannerConfigurer mapperScannerConfigurer=new MapperScannerConfigurer();
            mapperScannerConfigurer.setBasePackage("com.scidag.dao");
            return mapperScannerConfigurer;
        }
    }
    ​
  5. 创建ServletConfig

    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[]{"/"};
        }
    }
    ​
  6. 创建Dao和Service

    public interface BookDao {
        @Insert("insert into tbl_book (name,type,description)  values(#{name}, #{type}, #{description})")
        void save(Book book);
        @Delete("delete from tbl_book where id=#{id}")
        void delete(Integer id);
        @Update("update tbl_book set type=#{type}, name=#{name}, description=#{description} where id=#{id}")
        void update(Book book);
        @Select("select * from tbl_book where id =#{id}")
        Book  selectByID(Integer id);
        @Select("select * from tbl_book")
        List<Book> selectAll();
    }
    ​
    ​
    ​
    public interface BookService {
    ​
        /**
         * 保存
         * @param book
         * @return
         */
        boolean save(Book book);
    ​
        /**
         * 删除
         * @param id
         * @return
         */
        boolean delete(Integer id);
    ​
        /**
         * 修改
         * @param book
         * @return
         */
        boolean update(Book book);
    ​
        /**
         * 查单个
         * @param id
         * @return
         */
        Book  selectByID(Integer id);
    ​
        /**
         * 查所有
         * @return
         */
        List<Book> selectAll();
    }
    ​
    @Service
    public class BookServiceImpl implements BookService {
        @Autowired
        private BookDao bookDao;
        @Override
        public boolean save(Book book) {
            bookDao.save(book);
            return true;
        }
    ​
        @Override
        public boolean delete(Integer id) {
            bookDao.delete(id);
            return true;
        }
    ​
        @Override
        public boolean update(Book book) {
            bookDao.update(book);
            return true;
        }
    ​
        @Override
        public Book selectByID(Integer id) {
    ​
            return   bookDao.selectByID(id);
        }
    ​
        @Override
        public List<Book> selectAll() {
            return bookDao.selectAll();
        }
    }

  7. 创建pojo

    对应数据库中的属性名和类型,提供对应的get set toString 方法即可
  8. 创建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(Integer id){
            return bookService.delete(id);
        }
        @GetMapping("/{id}")
        public Book selectByID(Integer id)
        {
            return bookService.selectByID(id);
    ​
        }
        @GetMapping
        public List<Book> selectAll(){
            return  bookService.selectAll();
        }
    }
    ​
1.2统一结果封装

对于3.1来说,返回结果的boolean类型数据,而select则返回的一个对象

为了返回一个统一的数据结果,前端解析更简单.

  • 设置一个统一返回结果类

Result class... {

private Object data; private Integer code; private String msg;

}

  • 定义返回码状态类

//状态码
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;
}
  • colltroller中使用

@PostMapping
    public Result save(@RequestBody Book book){
        boolean save = bookService.save(book);
        return new Result(save? Code.insert_success:Code.insert_err,save) ;
    }
1.3统一异常处理

异常种类和异常原因

框架内部抛出的异常:因使用不合规导致 数据层抛出的异常:因外部服务器故障导致(例如:服务器访问超时) 业务层抛出的异常:因业务逻辑书写错误导致(例如:遍历业务书写操作,导致索引异常等) 表现层抛出的异常:因数据收集、校验等规则导致(例如:不匹配的数据类型间导致异常) 工具类抛出的异常:因工具类书写不严谨不够健壮导致(例如:必要释放的连接长期未释放等)

处理方式:新建一个异常包,新建异常类

package com.scidag.Exception;
​
public class BusinessException extends RuntimeException{
    private  Integer code;
​
    public BusinessException() {
    }
​
    public BusinessException(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;
    }
​
    public BusinessException(Throwable cause, Integer code) {
        super(cause);
        this.code = code;
    }
​
    public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Integer code) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.code = code;
    }
​
    public Integer getCode() {
        return code;
    }
​
    public void setCode(Integer code) {
        this.code = code;
    }
}
​
​
​
​
--------------------------------------------------
package com.scidag.Exception;
​
public class SystemExcrption extends  RuntimeException{
    private Integer code;
​
    public SystemExcrption(Integer code) {
        this.code = code;
    }
​
    public SystemExcrption() {
    }
​
    public SystemExcrption(String message, Integer code) {
        super(message);
        this.code = code;
    }
​
    public SystemExcrption(String message, Throwable cause, Integer code) {
        super(message, cause);
        this.code = code;
    }
​
    public SystemExcrption(Throwable cause, Integer code) {
        super(cause);
        this.code = code;
    }
​
    public SystemExcrption(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Integer code) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.code = code;
    }
​
    public Integer getCode() {
        return code;
    }
​
    public void setCode(Integer code) {
        this.code = code;
    }
}
---------------------------
controller
package com.scidag.controller;
​
import com.scidag.Exception.BusinessException;
import com.scidag.Exception.SystemExcrption;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
​
@RestControllerAdvice
public class ProjectExcptionAdvice {
    @ExceptionHandler(SystemExcrption.class)
    public Result doSystemExcrption(SystemExcrption e){
​
        return  new Result(e.getCode(),null ,e.getMessage());
    }
    @ExceptionHandler(BusinessException.class)
    public Result doBusinessExcrption(BusinessException e){
​
        return  new Result(e.getCode(),null ,e.getMessage());
    }
    @ExceptionHandler(Exception.class)
    public Result doExcrption(Exception e){
        System.out.println("有异常");
        return  new Result(Code.SYSTEM_UNKNOW_ERR,null ,"处理异常");
    }
}
​

相关文章:

  • MySQL MVCC的快照读和当前读区别,Redis的RDB+AOF混合持久化流程。
  • 用SVG绕过浏览器XSS审计
  • Axure项目实战:智慧城市APP(五)新闻资讯、就业信息(动态面板)
  • 微调0.5 B-32B模型要达到85%的准确率需要的数据和资源-会话质检和会话小结
  • 比手动备份快 Iperius全自动加密备份,NAS/云盘/磁带机全兼容
  • MagicFlow-防火墙网关-任意文件读取漏洞
  • 如何面对自己有意识和无意识的逃避(一)
  • c++R 格式
  • 超融合服务器是什么
  • python中使用openssl构建root证书,CSR,并验证
  • Go 语言 fmt 模块的完整方法详解及示例
  • 标星 62.9 万,8 个 yyds 的 GitHub 开源项目 !
  • C++中的std::move函数详解:移动语义与资源管理
  • golang结构体与指针类型
  • ARM day2
  • protobuf为什么快
  • 基于ssm的微博网站(全套)
  • 流量分析2
  • VectorBT:使用PyTorch+LSTM训练和回测股票模型 进阶二
  • 核心知识——论文详解
  • 体坛联播|热刺追平单赛季输球纪录,世俱杯或创收20亿美元
  • 张家界一铁路致17人身亡,又有15岁女孩殒命,已开始加装护栏
  • 普京调整俄陆军高层人事任命
  • 外交部:各方应为俄乌双方恢复直接对话创造条件
  • 多条跨境铁路加速推进,谁是下一个“超级枢纽”?
  • 大外交|巴西总统卢拉第六次访华签署20项协议,“双方都视对方为机遇”