REST 控制器中的 Spring Boot 绑定和验证错误处理

2023-11-23

当我有以下带有 JSR-303(验证框架)注释的模型时:

public enum Gender {
    MALE, FEMALE
}

public class Profile {
    private Gender gender;

    @NotNull
    private String name;

    ...
}

以及以下 JSON 数据:

{ "gender":"INVALID_INPUT" }

在我的 REST 控制器中,我想处理两个绑定错误(无效的枚举值)gender属性)和验证错误(name属性不能为空)。

以下控制器方法不起作用:

@RequestMapping(method = RequestMethod.POST)
public Profile insert(@Validated @RequestBody Profile profile, BindingResult result) {
    ...
}

这给出了com.fasterxml.jackson.databind.exc.InvalidFormatException绑定或验证发生之前发生序列化错误。

经过一番摆弄后,我想出了这个自定义代码,它可以实现我想要的功能:

@RequestMapping(method = RequestMethod.POST)
public Profile insert(@RequestBody Map values) throws BindException {

    Profile profile = new Profile();

    DataBinder binder = new DataBinder(profile);
    binder.bind(new MutablePropertyValues(values));

    // validator is instance of LocalValidatorFactoryBean class
    binder.setValidator(validator);
    binder.validate();

    // throws BindException if there are binding/validation
    // errors, exception is handled using @ControllerAdvice.
    binder.close(); 

    // No binding/validation errors, profile is populated 
    // with request values.

    ...
}

基本上,此代码的作用是序列化为通用映射而不是模型,然后使用自定义代码绑定到模型并检查错误。

我有以下问题:

  1. 自定义代码是这里的方法还是在 Spring Boot 中是否有更标准的方法?
  2. 如何@Validated注释工作?我怎样才能制作自己的自定义注释,其工作原理如下@Validated封装我的自定义绑定代码?

这是我在我的一个项目中使用的代码,用于在 Spring Boot 中验证 REST api,这与您的要求不同,但是相同的..检查这是否有帮助

@RequestMapping(value = "/person/{id}",method = RequestMethod.PUT)
@ResponseBody
public Object updatePerson(@PathVariable Long id,@Valid Person p,BindingResult bindingResult){
    if (bindingResult.hasErrors()) {
        List<FieldError> errors = bindingResult.getFieldErrors();
        List<String> message = new ArrayList<>();
        error.setCode(-2);
        for (FieldError e : errors){
            message.add("@" + e.getField().toUpperCase() + ":" + e.getDefaultMessage());
        }
        error.setMessage("Update Failed");
        error.setCause(message.toString());
        return error;
    }
    else
    {
        Person person = personRepository.findOne(id);
        person = p;
        personRepository.save(person);
        success.setMessage("Updated Successfully");
        success.setCode(2);
        return success;
    }

成功.java

public class Success {
int code;
String message;

public int getCode() {
    return code;
}

public void setCode(int code) {
    this.code = code;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}
}

错误.java

public class Error {
int code;
String message;
String cause;

public int getCode() {
    return code;
}

public void setCode(int code) {
    this.code = code;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public String getCause() {
    return cause;
}

public void setCause(String cause) {
    this.cause = cause;
}

}

您还可以在这里查看:Spring REST 验证

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

REST 控制器中的 Spring Boot 绑定和验证错误处理 的相关文章

随机推荐