Spring 4.1.5 MVC @RequestParam(required = false,value =" somevalue")如果参数不存在则失败

时间:2016-01-04 21:06:24

标签: java spring spring-mvc spring-restcontroller

我有一个spring mvc控制器,它提供多个请求参数的Web服务请求。所有参数都标记为required = false。如果请求中的参数不可用,

@RequestMapping(value = "/service/deployNew", method = RequestMethod.POST)
@ResponseBody public ResponseEntity<DeploymentId>  deploy(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false, value = "abc") String abc, @RequestParam(required = false, value = "xyz") String xyz, @RequestParam(required = false, value = "uvw") String uvw,)  throws Exception;

我看到了错误

required string parameter 'param' is not present

如果我给参数一个空白值,一切正常,如下所示。参数abcxyz有一个空白值,但我仍在传递它。

curl -i -X POST -H Accept:application/json "http://localhost:8080/Test/service/deploy.do?abc=&xyz=&uvw=somevalue"

如果我删除上述任何一个参数,它将抛出错误。

curl -i -X POST -H Accept:application/json "http://localhost:8080/Test/service/deploy.do?uvw=somevalue"

多个客户端使用我的服务,只有一个端点导致某些参数有时出现。我需要处理所有场景。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

尝试使用defaultValue

@RequestParam(required = false, defaultValue = "somevalue")

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html#defaultValue--