【问题标题】:How to validate JSON @RequestBody using org.springframework.validation.Validator in Spring WebFlux?如何在 Spring WebFlux 中使用 org.springframework.validation.Validator 验证 JSON @RequestBody?
【发布时间】:2018-02-05 07:34:53
【问题描述】:

我正在尝试在 Spring WebFlux 中使用 org.springframework.validation.Validator 验证 JSON @RequestBody,但我收到“内部服务器错误”并显示以下消息。

java.lang.IllegalStateException: Failed to resolve argument 1 of type 'org.springframework.validation.BindingResult' on public reactor.core.publisher.Mono ....

验证器类:

@Component
public class GreetingValidator implements Validator {

    @Override
    public boolean supports(Class<?> type) {
        return GreetingSchema.class.equals(type);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, "content", "content.empty", "Content is required");
        GreetingSchema greeting = (GreetingSchema) obj;
    }

}

REST 控制器类:

@RestController
@RequestMapping("/greeting")
public class GreetingController {

    @Autowired
    private GreetingValidator validator;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(validator);
    }

    @GetMapping
    public GreetingSchema get() {
        return new GreetingSchema("Hello, World!");
    }

    @PostMapping(consumes = "application/json")
    public Mono post(@Validated @RequestBody GreetingSchema body, BindingResult result) {
        if (result.hasErrors()) {
            return Mono.just(result.getFieldErrors());
        }
        return Mono.just("valid");
    }
}

当我从 post 方法中删除 @RequestBody 注释后尝试如下

public Mono post(@Validated GreetingSchema body, BindingResult result)

然后它在没有“内部服务器错误”的情况下运行,但无法验证 JSON @RequestBody。

{"content": "Hello, Xyz!"}

【问题讨论】:

  • 我使用的是spring-boot RC1。

标签: json spring validation spring-webflux spring-validator


【解决方案1】:

我没有配置 WebDataBinder。
我的代码:
控制器是这样的

@PostMapping(value = "/url")
public Mono<Result> method(@RequestBody @Validated Message message) {
    long time1 = System.currentTimeMillis();
    //do sth
    long time2 = System.currentTimeMillis();
    return Mono.just(Result.withData(time2 - time1));
}

类Message是这样的

@Getter
@Setter
public class Message implements Serializable {
    private String content;

    @Range(min = 1,max = 3)
    private int length;

    @NotNull
    private String publisher;
}

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2020-03-29
    • 2020-07-26
    • 2021-02-07
    • 2022-01-17
    • 2019-09-26
    • 2017-03-13
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多