Spring MVC 模型验证

模型验证

使用spring-boot-starter-validation 校验参数

导入包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

springboot-2.3开始,校验包被独立成了一个starter组件,所以需要引入validation和web,而springboot-2.3之前的版本只需要引入 web 依赖就可以了。

常用注解

注解 说明
@NotNull 使用在Bean的字段注解中。它是 JSR303(Bean的校验框架)的注解,在controller的方法中验证时(运行时检查一个属性是否为空)使用,如果不合法(为空),注解中的提示信息会保存在result中。
@Null 被注释的元素必须为null
@NotNull 被注释的元素不能为null,可以为空字符串
@AssertTrue 被注释的元素必须为true
@AssertFalse 被注释的元素必须为false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max,min) 被注释的元素的大小必须在指定的范围内。
@Digits(integer,fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(value) 被注释的元素必须符合指定的正则表达式。
@Email 被注释的元素必须是电子邮件地址
@Length 被注释的字符串的大小必须在指定的范围内
@Range 被注释的元素必须在合适的范围内
@NotEmpty 用在集合类上,不能为null,并且长度必须大于0
@NotBlank 只能作用在String上,不能为null,而且调用trim()后,长度必须大于0

配置校验的模型

import lombok.Data;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotEmpty;


@Data
public class UserDto {
    @Length(min = 6,max = 18,message = "password长度必须位于6到18之间")
    private String password;
    @NotEmpty(message = "请填写手机号")
    private String mobile;
}

在Controller中校验

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 类注解
 */
@RestController
@RequestMapping("test")
public class TestController {
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public UserDto Test(@Validated UserDto user){
        return u;
    }
}

直接请求会抛出异常

这里我们使用@ControllerAdvice处理全局异常

定义全局模型异常处理类

package com.example.demo.filters;

import java.util.List;

import com.example.demo.R;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BindException.class)
    public R exceptionHandle(BindException exception) {

        BindingResult result = exception.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();

        List<FieldError> fieldErrors = result.getFieldErrors();
        fieldErrors.forEach(error -> {
            errorMsg.append(error.getDefaultMessage()).append("!");
        });
        return R.Error(errorMsg.toString());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R MyExceptionHandle(MethodArgumentNotValidException exception) {

        BindingResult result = exception.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();

        List<FieldError> fieldErrors = result.getFieldErrors();
        fieldErrors.forEach(error -> {
            errorMsg.append(error.getDefaultMessage()).append("!");
        });

        return R.Error(errorMsg.toString());
    }

    // 处理运行时异常
    @ExceptionHandler(RuntimeException.class)
    public R doHandleRuntimeException(RuntimeException e) {
        e.printStackTrace();
        return R.Error(e.getMessage());
    }
}

接口统一返回类

package com.example.demo;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class R {
    private int code;
    private String msg;
    private Object data;


    public static R Error(String msg){
        return  new R(1,msg,"");
    }

    public  static R Success(){
        return new R(0,"",null);
    }

    public  static R Success(Object data){
        return new R(0,"",data);
    }
    public  static R Success(Object data,String msg){
        return new R(0,msg,data);
    }
}

引用:

spring-boot-starter-validation 校验参数 - _lemonV - 博客园 (cnblogs.com)

原文地址:https://www.cnblogs.com/qs315/p/15692553.html