BeanPropertyBindingResult

文章目录

  • 前言
  • 一、main & User
  • 二、console


前言

采集实体类异常,在controller校验入参


一、main & User

package com.example.demo.testJava;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;

@RestController
public class main {

    @Resource
    private Validator validator;

    @PostMapping(value = "/aaa")
//    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    public void updateConfig() {
        User user = new User("1","张三");

        BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(user, "user");
        validator.validate(user, bindingResult);
        System.out.println(bindingResult.getObjectName());
        if (bindingResult.hasErrors()) {
            System.out.println(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

    }

}

class User {
    public User(String id, String name) {
        this.id = id;
        this.name = name;
    }
    @NotBlank(message = "名称不能为空")
    String id;

    @Pattern(regexp = "[a-zA-Z]",message = "名称格式不合法")
    String name;


}

二、console

user
名称格式不合法

你可能感兴趣的:(java,java)