如何限制Spring Rest Api中post方法中的查询参数?

sen*_*sen 2 java rest spring spring-mvc

如何限制Spring Rest Api中post方法中的查询参数?

网址:http://localhost:9003/test-api/getDetails

请求体:

{
  "name": "TestUser",
  "age": 25,
  "Email": "abc@test.com"

}
Run Code Online (Sandbox Code Playgroud)

在上面的 URL 中,如果有如下获取查询参数,我们应该抛出错误/限制 http://localhost:9003/test-api/getDetails?dateOfBirth=26081992

我的代码:

@RequestMapping(value = "/getDetails", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public @ResponseBody ResponseEntity<String> TestMethod(
            @Valid @RequestBody CustomerDetails customerDetails, BindingResult result,
             HttpServletRequest request) {
             //..some Actions
             }
Run Code Online (Sandbox Code Playgroud)

cas*_*lin 5

您可以将所有查询参数绑定到 aMap<String, String>MultiValueMap<String, String>using @RequestParam。从文档

如果方法参数是 Map<String, String>orMultiValueMap<String, String>并且未指定参数名称,则 map 参数将填充所有请求参数名称和值。

就像是:

@RequestMapping(value = "/foo", method = RequestMethod.POST)
public ResponseEntity<String> foo(@RequestParam Map<String, String> requestParams,
                                  @RequestBody Foo foo) {
    ...     
}
Run Code Online (Sandbox Code Playgroud)

400如果地图包含无效值,则拒绝使用状态代码的请求。