小编典典

Spring Boot REST @RequestParam未通过验证

spring-boot

我已经从网上尝试了许多示例,但无法让Spring验证我的查询字符串参数。似乎不执行REGEX /失败。

package my.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.Pattern;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
public class MyController {

    private static final String VALIDATION_REGEX = "^[0-9]+(,[0-9]+)*$";

    @RequestMapping(value = "/my/{id}", method = GET)
    public myResonseObject getMyParams(@PathVariable("id") String id,
                                       @Valid @Pattern(regexp = VALIDATION_REGEX) 
                                       @RequestParam(value = "myparam", required = true) String myParam) {
         // Do Stuff!
    }

}

当前行为

PASS - /my/1?myparam=1
PASS - /my/1?myparam=1,2,3
PASS - /my/1?myparam=
PASS - /my/1?myparam=1,bob

期望的行为

PASS - /my/1?myparam=1
PASS - /my/1?myparam=1,2,3
FAIL - /my/1?myparam=
FAIL - /my/1?myparam=1,bob

谢谢


阅读 463

收藏
2020-05-30

共1个答案

小编典典

您需要像这样将@Validated添加到您的类中:

@RestController
@Validated
class Controller {
  // ...
}

更新

您需要对其进行适当的配置..将此bean添加到您的上下文中:

@Bean
 public MethodValidationPostProcessor methodValidationPostProcessor() {
      return new MethodValidationPostProcessor();
 }

处理异常的示例

@ControllerAdvice
@Component
public class GlobalExceptionHandler {
    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map handle(MethodArgumentNotValidException exception) {
        return error(exception.getBindingResult().getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList()));
    }


    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map handle(ConstraintViolationException exception) {
        return error(exception.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.toList()));
    }

    private Map error(Object message) {
        return Collections.singletonMap("error", message);
    }
}
2020-05-30