简体   繁体   English

多个@RequestParam的Spring验证

[英]Spring Validation for multiple @RequestParam

Suppose I have a RestController for a @GetMapping as below 假设我有一个@GetMapping的RestController,如下所示

ResponseEntity<?> getXXX(
@RequestParam(value = "param1", required = true) String param1,
@RequestParam(value = "param2", required = true) String param1)

if consumer performs @Get for this API without param1 and param2, Spring will throw the "MissingServletRequestParameterException" but only for the param1 but param2 如果使用者对此API执行@Get而不使用param1 param2,则Spring会抛出“ MissingServletRequestParameterException”,但针对param1而非param2

My question here is if consumer doesn't pass both param1 and param2, could we somehow get MissingServletRequestParameterException for both param1 and param2? 我在这里的问题是,如果消费者没有通过这两个参数1和参数,我们可以某种方式得到MissingServletRequestParameterException 两个参数1和参数?

Please advice me 请告诉我

First of all, this code won't compile since you have redeclared a variable within a scope. 首先,由于您已在作用域内重新声明了变量,因此无法编译此代码。 Moreover, if I understood the question correctly, if you refactor the given snippet of code (so that it compile), spring will throw an exception when notice the first required parameter is missing just like jvm throws NullPointerException in analogous situation with information about exception only in line with exception: 而且,如果我正确理解了这个问题,如果您重构给定的代码段(以便进行编译),则在通知缺少第一个必需参数时,spring将引发异常,就像jvm在类似情况下仅抛出有关异常信息的NullPointerException异常一样符合例外:

String a = null;
String b = null;
a.length();      //NullPointerException exception thrown
b.length();

You have to create your custom validator checking if parameters were given in request and if not, throw an appropriate exception. 您必须创建自定义验证器,以检查是否在请求中指定了参数,如果没有,则抛出适当的异常。 Something like: 就像是:

void validate(String param1, String param2) {
        Stream.of(param1, param2).filter(Objects::nonNull).findAny().orElseThrow(() -> new IllegalArgumentException("param1 and param2 are missing"));
        Optional.ofNullable(param1).orElseThrow(() -> new IllegalArgumentException("param1 is missing"));
        Optional.ofNullable(param2).orElseThrow(() -> new IllegalArgumentException("param2 is missing"));
    }

with an exception you'd like to throw. 除了您要抛出的异常。 If you want to do it this way, set values of "required" flags to false. 如果要用这种方法,请将“ required”标志的值设置为false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM