SpringBoot validator 参数校验器和全局异常拦截器

依赖

		
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-validationartifactId>
        dependency>

        
        <dependency>
            <groupId>javax.xml.bindgroupId>
            <artifactId>jaxb-apiartifactId>
            <version>2.3.0version>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.1.1version>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.9.2version>
        dependency>
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.9.2version>
        dependency>
        
        <dependency>
            <groupId>com.github.xiaoymingroupId>
            <artifactId>swagger-bootstrap-uiartifactId>
            <version>1.9.3version>
        dependency>

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.47version>
        dependency>
        
        
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.4version>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.9version>
        dependency>

        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-generatorartifactId>
            <version>3.1.1version>
        dependency>

        
        <dependency>
            <groupId>org.apache.velocitygroupId>
            <artifactId>velocity-engine-coreartifactId>
            <version>2.1version>
        dependency>
        
        <dependency>
            <groupId>org.freemarkergroupId>
            <artifactId>freemarkerartifactId>
            <version>2.3.28version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.2.0version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

统一返回结构


import lombok.Data;

@Data
public class Ret<T> {
    private int code;
    private String msg;
    private T data;

    public Ret(){
        this.msg = "";
    }

    public Ret success(String msg){
        return success(msg,null);
    }
    public Ret success(String msg,T data){
        return init(200,msg,data);
    }
    public Ret success(T data){
        return success("",data);
    }

    public Ret error(String msg){
        return error(msg,null);
    }
    
    public Ret error(String msg,T data){
        return init(500,msg,data);
    }
    public Ret error(T data){
        return error("",data);
    }

    public Ret badRequest(String msg){
        return badRequest(msg,null);
    }

    public Ret badRequest(String msg,T data){
        return init(400,msg,data);
    }
    public Ret badRequest(T data){
        return badRequest("",data);
    }

    public Ret init(int code,String msg,T data){
        this.code = code;
        this.msg = msg;
        this.data = data;
        return this;
    }
}



SpringBoot validator 参数校验器和全局异常拦截器_第1张图片

全局异常拦截器

import com.humorchen.pastry_examination.dto.Ret;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.BindException;

/**
 * 全局异常处理配置
 */
@ControllerAdvice
public class GlobalExceptionHandler {

   @ExceptionHandler(value = {BindException.class, HttpMessageNotReadableException.class,MethodArgumentNotValidException.class, ConstraintViolationException.class, MissingServletRequestParameterException.class})
    @ResponseBody
    public Ret argumentNotValidExceptionHandler(Exception e){
        Ret ret = new Ret();
        ret.badRequest("请求异常",e.getMessage());
        return ret;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Ret defaultExceptionHandler(Exception e){
        Ret ret = new Ret();
        ret.error("处理异常",e.getMessage());
        return ret;
    }

可用的注解

Constranit desc
@Null 被注解的元索必须为空
@notNull 被注解的元素必须不为空
@Min 被注解的元素必须是数字且必须小于等于指定值
@Max 被注解的元素必须是数字且必须大于等于指定值
@Past 被注解的元索必须是- -个过去的日期
@Future 被注解的元素必须是一个将来的日期
@Pattern 被注解的元素必须符合给定的正则表达式
@AssertTure 被注解的元素必须为ture
@AssertFalse 被注解的元素必须为false
@Email 被注解的元素必须是email地址
@Length 被注解的元素必须在指定的范围内
@NotEmpty 被注解的元素是必须
@Range 被注解的元素可以是数字或者是数字的字符串必须在指定的范围内
@URL 被注解的元素必须是一个URL

实体标注注解声明校验条件


import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import javax.validation.constraints.*;

/**
 * 

* 考试 *

* * @author humorchen * @since 2021-06-12 */
@Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("t_examination") @ApiModel(value="Examination对象", description="考试") public class Examination implements Serializable { private static final long serialVersionUID=1L; @ApiModelProperty(value = "ID") @TableId(value = "id", type = IdType.AUTO) private Integer id; @ApiModelProperty(value = "考试名") @TableField("name") @NotBlank(message = "考试名不能为空") private String name; @ApiModelProperty(value = "时间限制") @TableField("limit_time") @NotNull @Min(value = 1000,message = "考试时长限制必须大于1000") private Integer limitTime; @ApiModelProperty(value = "总分数") @TableField("score") private Integer score; @ApiModelProperty(value = "时间") @TableField("time") private Long time; @ApiModelProperty(value = "字符串时间") @TableField("timeStr") private String timeStr; public static final String ID = "id"; public static final String NAME = "name"; public static final String LIMIT_TIME = "limit_time"; public static final String SCORE = "score"; public static final String TIME = "time"; public static final String TIMESTR = "timeStr"; }

单个参数标注校验

 @GetMapping("/list")
    @ApiOperation("列出所有考试")
    public Ret<List<Examination>> list(@Min(value = 100,message = "最小100") @RequestParam int page){
        Ret ret = new Ret();

        return ret;
    }

完整Controller代码


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.humorchen.pastry_examination.DateUtil;
import com.humorchen.pastry_examination.bean.Examination;
import com.humorchen.pastry_examination.dto.Ret;
import com.humorchen.pastry_examination.service.IExaminationService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 

* 考试 前端控制器 *

* * @author humorchen * @since 2021-06-12 */
@RestController @RequestMapping("/examination") public class ExaminationController { @PostMapping("/add") @ApiOperation("添加考试") public Ret add (@RequestBody @Validated Examination examination){ Ret ret = new Ret(); //your code return ret; } @GetMapping("/list") @ApiOperation("列出所有考试") public Ret<List<Examination>> list(@Min(value = 100,message = "最小100") @RequestParam int page){ Ret ret = new Ret(); return ret; } }

实体类校验

例如@NotBlank(message = “考试名不能为空”)

SpringBoot validator 参数校验器和全局异常拦截器_第2张图片

时间限制必须不为空且大于1000

SpringBoot validator 参数校验器和全局异常拦截器_第3张图片

单个参数校验

例如不能小于100

SpringBoot validator 参数校验器和全局异常拦截器_第4张图片

你可能感兴趣的:(Java,spring,boot,validator)