Spring 4.1.5 MVC @RequestParam(required = false, value = “somevalue”) fails if a parameter is absent

梦想的初衷 提交于 2019-12-22 11:35:50

问题


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



来源:https://stackoverflow.com/questions/34599842/spring-4-1-5-mvc-requestparamrequired-false-value-somevalue-fails-if-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!