Spring MVC - @RequestParam throwing MissingServletRequestParameterException with x-www-form-urlencoded
The following Spring MVC code throws MissingServletRequestParameterException,
@Controller
@RequestMapping("/users")
public class XXXXResource extends AbstractResource {
.....
@RequestMapping(method = RequestMethod.PUT
, produces = {"application/json", "application/xml"}
, consumes = {"application/x-www-form-urlencoded"}
)
public
@ResponseBody
Representation createXXXX(@NotNull @RequestParam("paramA") String paramA,
@NotNull @RequestParam("paramB") String paramB,
@NotNull @RequestParam("paramC") String paramC,
@NotNull @RequestParam("paramD") String paramD ) throws Exception {
...
}
}
There are no stack traces in the logs, only a request from Postman returns with an HTTP 400 error.
source to share
if you want Content-type:application/x-www-form-urlencoded
means that the body of the HTTP request sent to the server should be one giant line: the name / value of the pair are ampersand-separated (&)
and would be urlencoded
as its name entails.
name=name1&value=value2
this means the user doesn't have to @RequestParam
, because the arguments are passed in the body of the http request.
So, if you want to use this one content-type
from your doc:
You convert the request body to a method argument using the HttpMessageConverter. The HttpMessageConverter is responsible for converting from an HTTP request message to an object and converting from an object to an HTTP response body. RequestMappingHandlerAdapter supports @RequestBody annotation using the following standard HttpMessageConverters:
ByteArrayHttpMessageConverter converts byte arrays.
StringHttpMessageConverter converts strings.
FormHttpMessageConverter converts form data to / from MultiValueMap.
SourceHttpMessageConverter converts to / from javax.xml.transform.Source.
You have to use @RequestBody
with FormHttpMessageConverter
, which will receive this giant string and convert it to MultiValueMap<String,String>
. Here's an example.
@RequestMapping(method = RequestMethod.PUT
, consumes = {"application/x-www-form-urlencoded"}
,value = "/choice"
)
public
@ResponseBody
String createXXXX(@RequestBody MultiValueMap params) throws Exception {
System.out.println("params are " + params);
return "hello";
}
source to share