SpringBoot整合SSM

目录

1、创建工作目录结构,修改为yml文件。

2 、统一web返回对象R类型。

 3、配置Swagger。

4、创建自定义异常类: 

5、精简返回给前端的异常消息 :

6、数据库以及tomcat服务器配置:

        1、配置tomcat服务器

         2、配置mySQL

         3、配置Radies(长短令牌用);

        4、配置MongoDB数据库:

        5、配置MyBatis (使用前要先添加插件)

7、配置权限与验证模块。

创建项目勾选的时候勾选三个关于数据库的,一个lombok工具以及SpringWeb即可。省着后期导入数据库的依赖

1、创建工作目录结构,修改为yml文件。

        1、controller类书写web方法,form是web方法中的接收的对象类型。

        2、db中的Dao是接口,定义方法用的。pojp是基于ORM生成的模型

修改 properties文件为yml格式,注意不要修改文件名,只修改扩展名

1、日志配置为警告才显示,并且将时间进行格式化:

logging:
  level:
    root: info
    com.example.mineemos.db.dao: warn 让这个文件下的日志只有警告类型的数据才会打印出来
  partten:
    console: "%d{HH:mm:ss} %-5level %msg%n" 格式化时间

2、controller类中form包书写示例:

想接收一个对象前面要加@RequestBody注解,并且必须是PostMapping(spring包的)注解。要用注释加@Valid(javax包下的)以简单的登录验证为例

controller类:

package com.example.mineemos.controller;

import com.example.mineemos.ReturnObj.R;
import com.example.mineemos.controller.form.signForm;
import com.example.mineemos.service.impl.signImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/sign")
@Tag(name = "登录模块")
public class signController {
    @Autowired
    private signImpl signService;

    @PostMapping("/signs")
    @Operation(summary = "验证登录")
    public R sign(@Valid @RequestBody signForm info){
        signService.canSign(info.getUserName(),info.getPassWord());
        return new R().put("code",200).put("msg","登陆成功");
    };
}

接收参数的form类

如果为满足注解的条件,前端用res.data即可打印出错误信息

package com.example.mineemos.controller.form;

import lombok.Data;
import javax.validation.constraints.NotBlank;

@Data
public class signForm {
    @NotBlank(message = "账号不能为空")//不满足就会返回这样的信息
    private String userName;
    @NotBlank(message = "密码不能为空")//状态码是500
    private String passWord;
}

2 、统一web返回对象R类型。

1、需要导入的Http状态码依赖。

2、R类要继承HashMap类。 

返回给前端的对象数数据存在res.data.绑定的变量名,中,而不是直接res.变量名

        <!--给R对象返回的Http状态码-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.13</version>
        </dependency>
import org.apache.http.HttpStatus;
import java.util.HashMap;
import java.util.Map;

public class R extends HashMap<String,Object> {
    //初始化对象时候就添加两条信息
    public R(){
        //创建对象时默认放进去一些数据
        //HttpStatus导入那个依赖里自带的
        //HttpStatus.SC_OK是一个常量=200
        put("code", HttpStatus.SC_OK);
        put("msg","success");
    }
    //实现了链式调用,本身的map集合不能链式添加,所以给他写一个
    public R put(String key,Object value){
        super.put(key,value);
        return this;
    }

    //ok表示请求成功
    public static R ok(){
        return new R();
    }
    public static R ok(String msg){
        R r=new R();
        //已经有message方法了,再写就会将其覆盖
        r.put("msg",msg);
        return r;
    }
    public R ok(int code,String msg){
        R r=new R();
        r.put("code",code).put("msg",msg);
        return r;
    }
    public static R ok(Map<String,Object> map){
        R r=new R();
        r.putAll(map);
        return r;
    }

    //表示请求失败
    public static R error(int code,String msg){
        R r=new R();
        r.put("code",code);
        r.put("msg",msg);
        return r;
    }
    public static R error(String msg){
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR,msg);
    }
    public static R error(){
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR,"未知异常,请联系管理员");
    }

}

如果后台抛出异常,前台res.data即可打印异常信息,如果正常返回数据用res.绑定的变量名,即可得到对应的数据。

 3、配置Swagger。

详情见文章:​​​​​​swagger3配置超简洁

SpringDoc依赖;

     <!--添加springDoc依赖-->
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-spring-boot-2-webmvc</artifactId>
            <version>3.1.5</version>
        </dependency>

 配置yml文件

springdoc:
  api-docs:
    enabled: true
    path: /你自己的项目名称.html
  swagger-ui:
    path: /swagger-ui.html
    disable-swagger-default-url: on
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

4、创建自定义异常类: 

1、加上Set个get方法。          2、继承RuntimeException类        3、code和message属性即可

import lombok.Data;
@Data
//异常类
public class EmosException extends RuntimeException{
    private int code=500;
    private String msg;

    //前两个构造方法常用后面的两个不常用

    //对该异常类的构造方法进行补充,不写的化会默认只有一个无参构造
    public EmosException(String msg) {
        super(msg);//将错误信息以红色的方式打印在控制台
        this.msg = msg;
    }

    public EmosException(String msg, int code) {
        super(msg);
        this.msg = msg;
        this.code = code;
    }

    public EmosException(String msg, Throwable e) {
        super(msg, e);
        this.msg = msg;
    }

    public EmosException(String msg, int code, Throwable e) {
        super(msg, e);
        this.msg = msg;
        this.code = code;
    }

}

5、精简返回给前端的异常消息 :

设置一个配置类,去配置这个简化的消息,不断的if判断,是哪一类就返回给哪个,返回给前端之后用回调函数res.data即可显示出异常消息

import com.example.emos.exception.EmosException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice//让系统知道这是处理异常的类
//步骤:1、将异常转化为对应的类型 2、调用里面的获取消息模块
public class ExceptionAdvice {
    @ResponseBody//将异常的返回格式为json格式
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)//处理哪种异常
    public String exceptionHandler(Exception e){
        log.error("-----执行异常-----"+e);//将异常打印在控制台
        //处理后端验证失败
        if(e instanceof MethodArgumentNotValidException){
            //将异常强转为验证异常
            MethodArgumentNotValidException exception= (MethodArgumentNotValidException) e;
            //获取异常消息
            return exception.getBindingResult().getFieldError().getDefaultMessage();
        }
        //自定义异常
        else if(e instanceof EmosException){
            EmosException exception= (EmosException) e;
            return exception.getMsg();
        }
        //未授权类型
        else if(e instanceof UnauthorizedException){
            return "你不具备相关权限";
        }
        else{
            return "后端执行异常";
        }
    }
}

6、数据库以及tomcat服务器配置:

        1、配置tomcat服务器

server:
  port: 8080  #端口
  servlet:
    context-path: /emos    #整个项目有个前缀,在路由前+该前缀才能访问

         2、配置mySQL

使用连接池要先添加依赖:

        <!--数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3307/数据库名?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
      username: root
      password: 数据库密码
      initial-size: 8
      max-active: 16
      min-idle: 8
      max-wait: 60000
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false

         3、配置Radies(长短令牌用);

  redis:
    database: 0
    host: localhost
    port: 6379
    password: abc123456
    jedis:
      pool:
        max-active: 1000
        max-wait: -1ms
        max-idle: 16
        min-idle: 8

        4、配置MongoDB数据库:

  redis:
    database: 0
    host: localhost
    port: 6379
    password: abc123456
    jedis:
      pool:
        max-active: 1000
        max-wait: -1ms
        max-idle: 16
        min-idle: 8

        5、配置MyBatis (使用前要先添加插件)

在Dao中定义方法,service中写接口也是方法,service的impl文件中写具体的业务逻辑

        1、让IDEA链接上mySQL数据库。并添加数据库以及MyBatis的全部依赖:

        <!--数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--myBatis依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        2、用myBatis-generater生成pojo和dao(仅use-lombook)

3、给每一个Dao接口上面都加上@Mapper注解,同时清除xml和Dao中自带的各种方法

4、配置myBaties的yml配置:

一定要修改下面的路径,那个位置是项目名称

mybatis:
  mapper-locations: classpath*:mapper/*.xml
  type-aliases-package: com.example.项目名称.db.pojo  //pojo类的路径
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl //想将SQL语句打印在控制台就写这句,不想直接删除,项目上线时必须删除
    map-underscore-to-camel-case: true  //是否支持驼峰命名

7、配置权限与验证模块

        以便简洁开发我使用了Sa-token,文章地址:链接。

        有小伙伴用的Shiro和JWT开发,这篇文章使用的是这种传统开发。地址

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值