SpringBoot validator 参数校验器和全局异常拦截器
依赖
<!-- validation-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- jdk8+需要 -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<!-- mybatis的orm插件 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<!--springboot test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Swagger2 访问/swagger-ui.html#/-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--spring fox 其实就是spring-swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--引入ui包 bootstrap ui美化的 访问/doc.html-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.3</version>
</dependency>
<!-- fast json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!--文件上传和下载-->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!--阿里druid数据库链接依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<!-- mybatis-plus-generator-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.1</version>
</dependency>
<!-- mybatis-plus-generator-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.1</version>
</dependency>
<!-- mybatis-plus-generator-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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;
}
}
全局异常拦截器
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.*;
/**
* <p>
* 考试
* </p>
*
* @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;
/**
* <p>
* 考试 前端控制器
* </p>
*
* @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 = “考试名不能为空”)
时间限制必须不为空且大于1000
单个参数校验
例如不能小于100
本文来自博客园,作者:HumorChen99,转载请注明原文链接:https://www.cnblogs.com/HumorChen/p/18039603