加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:50:25 所属栏目:大数据 来源:网络整理
导读:当我有以下模型与JSR-303(验证框架)注释: public enum Gender { MALE,FEMALE}public class Profile { private Gender gender; @NotNull private String name; ...} 以及以下JSON数据: { "gender":"INVALID_INPUT" } 在我的REST控制器中,我想处理绑定错误(

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

public enum Gender {
    MALE,FEMALE
}

public class Profile {
    private Gender gender;

    @NotNull
    private String name;

    ...
}

以及以下JSON数据:

{ "gender":"INVALID_INPUT" }

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

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

@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.

    ...
}

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

我有以下问题:

>自定义代码是否可以在这里进行,或者在Spring Boot中有更标准的方法吗?
> @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

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;
}
}

Error.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 Validation

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读