问题描述
我有一个简单的控制器方法:
I have a simple Controller method :
@GetMapping("/search")
public List<Result> search(@RequestParam @Valid @NotNull @Size(min = 4) String query) {
return searchService.search(query);
}
当我省略查询"参数时,我得到一个 400 Bad Request,正如预期的那样.
When I omit the "query" parameter, I get a 400 Bad Request, as expected.
使用这些查询参数测试方法不起作用.
Testing the method with these query parameters doesn't work.
除了最后一个测试之外的所有测试都应该返回400 Bad Request".
All but the last test should return a "400 Bad Request".
"/search" --> actual 400 Bad Request, test passes
"/search?query=" --> actual 200 Ok, expected 400 because @Size(min=4)
"/search?query=a" --> actual 200 Ok, expected 400 because @Size(min=4)
"/search?query=ab" --> actual 200 Ok, expected 400 because @Size(min=4)
"/search?query=abc" --> actual 200 Ok, expected 400 because @Size(min=4)
"/search?query=abcd" --> actual 200 Ok, test passes
为什么忽略@Size(min=4) 注释?
Why is the @Size(min=4) annotation being ignored?
推荐答案
验证 RequestParameters 不是开箱即用的.
Validating RequestParameters does not work like that out of the box.
您可以将参数包装在一个类中
You could wrap the parameters in a class like
class SearchRequest {
@Size(min=4)
@NotNull
private String query;
...
}
然后将您的控制器代码更改为
Then change your controller code to
@GetMapping("/search")
public List<Result> search(@ModelAttribute @Valid SearchRequest searchRequest) {
return searchService.search(searchRequest.getQuery());
}
现在这是一种方法,你想要的可能可以使用类上的@Validated 注释来实现,但我对此一无所知,但它似乎在这里涵盖:https://sdqali.in/blog/2015/12/04/validating-requestparams-and-pathvariables-in-spring-mvc/
Now this is one way to do it, what you want is probably achievable using the @Validated annotation on the class, but I don't know anything about that but it seems to be covered here: https://sdqali.in/blog/2015/12/04/validating-requestparams-and-pathvariables-in-spring-mvc/
这篇关于Spring Controller:尽管 @Valid 和 @Size 未验证 RequestParam的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!