Spring校验框架的使用 @Validated

定义需要校验的类与字段

public class Book {

    @NotBlank(message = "书名不能为空!")
    private String name;

    @NotNull(message = "价格不能为空!")
    private Double price;

    @NotEmpty(message = "作者不能为空!")
    private List<String> author;
}

@NotEmpty :不能为null,且Size>0

@NotNull:不能为null,但可以为empty

@NotBlank:只用于String,不能为null且trim()之后size>0

在controller层加入校验注解

@Controller
public class TestController {

    @ResponseBody
    @GetMapping(value = "/test")
    public String test(@Validated Book book){ //加入@Validated注解使校验生效
        return "success";
    }
}

请求值不通过校验示例

{
  "timestamp": 1553779622190,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.validation.BindException",
  "errors": [
    {
      "codes": [
        "NotBlank.book.name",
        "NotBlank.name",
        "NotBlank.java.lang.String",
        "NotBlank"
      ],
      "arguments": [
        {
          "codes": [
            "book.name",
            "name"
          ],
          "arguments": null,
          "defaultMessage": "name",
          "code": "name"
        }
      ],
      "defaultMessage": "书名不能为空!",
      "objectName": "book",
      "field": "name",
      "rejectedValue": null,
      "bindingFailure": false,
      "code": "NotBlank"
    },
    {
      "codes": [
        "NotEmpty.book.author",
        "NotEmpty.author",
        "NotEmpty.java.util.List",
        "NotEmpty"
      ],
      "arguments": [
        {
          "codes": [
            "book.author",
            "author"
          ],
          "arguments": null,
          "defaultMessage": "author",
          "code": "author"
        }
      ],
      "defaultMessage": "作者不能为空!",
      "objectName": "book",
      "field": "author",
      "rejectedValue": null,
      "bindingFailure": false,
      "code": "NotEmpty"
    },
    {
      "codes": [
        "NotNull.book.price",
        "NotNull.price",
        "NotNull.java.lang.Double",
        "NotNull"
      ],
      "arguments": [
        {
          "codes": [
            "book.price",
            "price"
          ],
          "arguments": null,
          "defaultMessage": "price",
          "code": "price"
        }
      ],
      "defaultMessage": "价格不能为空!",
      "objectName": "book",
      "field": "price",
      "rejectedValue": null,
      "bindingFailure": false,
      "code": "NotNull"
    }
  ],
  "message": "Validation failed for object='book'. Error count: 3",
  "path": "/test"
}

可结合全局异常捕获,返回指定类型的值

import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
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 javax.servlet.http.HttpServletRequest;

/**
 * 全局异常捕获处理
 * @author 向振华
 * @date 2019年3月28日
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 所有验证异常捕获处理
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
    public Object validationExceptionHandler(Exception exception) {
        BindingResult bindResult = null;
        if (exception instanceof BindException) {
            bindResult = ((BindException) exception).getBindingResult();
        } else if (exception instanceof MethodArgumentNotValidException) {
            bindResult = ((MethodArgumentNotValidException) exception).getBindingResult();
        }
        String msg;
        if (bindResult != null && bindResult.hasErrors()) {
            msg = bindResult.getAllErrors().get(0).getDefaultMessage();
        }else{
            msg = "请求失败!";
        }
        return msg;
    }

    /**
     * 未知的异常捕获处理
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Object allUnknowExceptionHandler(HttpServletRequest request, Exception exception) {
        return "系统繁忙!";
    }
}

请求:http://localhost:8001/test

返回:书名不能为空!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值