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

时间:2017-09-13 13:28:39

标签: java spring rest spring-mvc

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

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

RequestBody:

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

}

在上面的URL中,如果有get query params如下,我们应该抛出error / restrict 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
             }

1 个答案:

答案 0 :(得分:4)

您可以使用Map<String, String>将所有查询参数绑定到MultiValueMap<String, String>@RequestParam。来自documentation

  

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

类似的东西:

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

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