Java Spring Boot REST @RequestParam 未被验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38614903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:28:17  来源:igfitidea点击:

Spring Boot REST @RequestParam not being Validated

javaspringspring-mvcspring-boot

提问by ptimson

I have tried a number of examples from the net and cannot get Spring to validate my query string parameter. It doesn't seem execute the REGEX / fail.

我从网上尝试了许多示例,但无法让 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!
    }

}

Current behaviour

当前行为

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

Desired behaviour

期望的行为

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

Thanks

谢谢

采纳答案by Jaiwo99

You need add @Validated to your class like this:

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

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

UPDATE:

更新

you need to configure it properly.. add this bean to your context:

您需要正确配置它.. 将此 bean 添加到您的上下文中:

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

Example to handle exception:

处理异常的示例

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

回答by Achille_vanhoutte

You can try this

你可以试试这个

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

(pay attention for the final modifier)or else

(注意最后的修饰符)否则

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

And then remove @Pattern(regexp = VALIDATION_REGEX)from your method and keep only the @Validannotation:

然后从您的方法中删除@Pattern(regexp = VALIDATION_REGEX)并仅保留@Valid注释:

public myResonseObject getMyParams(@PathVariable("id") String id, @Valid @RequestParam(value = "myparam", required = true) String myParam) {

回答by Gangnus

You have incorrect regex

你有不正确的正则表达式

"^[0-9]+(,[0-9]+)*$"

It will never parse

它永远不会解析

1,bob

Maybe, you need:

也许,你需要:

"^\w+(,\w+)*$"

And if you need to parse also an empty line, use:

如果您还需要解析一个空行,请使用:

"^(\w+(,\w+)*)?$"