Spring 4.1.5 MVC @RequestParam(required = false, v

2019-06-14 10:51发布

问题:

I have a spring mvc controller which is serving web service requests with multiple request parameters. All the parameters are marked required = false. Still if in the request a parameter is not available,

@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;

I see the error

required string parameter 'param' is not present

If I give a blank value to the param, everything works fine as below. Parameters abc and xyz has a blank value, but still I am passing it.

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

If I remove any of the above param it will throw the error.

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

My service is being used by multiple clients with a single endpoint which caused some parameters to be present at times. I need to handle all the scenarios. Any idea?

回答1:

Try to use defaultValue

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

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