请求参数校验

请求参数名称不符合

为了确保请求参数可以正确地映射到方法的参数上,需要确保请求参数名称与方法中的@RequestParam注解后面的名称相符。

@GetMapping("/book")
public String book(@RequestParam("name") String name, String author) {
    return null;
}

当请求参数和@RequestParam注解上提供的参数不匹配时,就会抛出MissingRequestValueException异常。

正确请求/api/books?name=西游记&author=120

错误请求/api/books?bookname=西游记&author=120

请求参数不符合校验规则

@GetMapping("/book")
public String book(@NotNull(message = "name不能为空") @RequestParam("name") String name, @NotNull(message = "author不能为空") String author) {
    return name + author;
}

在不添加@Validated注解时,当请求参数不符合规则时,会抛出HandlerMethodValidationException异常。

在类上添加@Validated时,当请求参数不符合娇艳规则时,会抛出ConstraintViolationException异常。

ServerWebInputException: 参数类型失败

请求参数不符合Bean

@GetMapping("/book")
public Object book(UserDto userDto) {
    return userDto;
}

WebExchangeBindException: 参数不匹配\参数类型无法正确映射

最后更新于

这有帮助吗?