0

In Spring 4 MVC, I'm trying to figure out how to accept both form parameters and query parameters posted to my rest endpoint and also trigger validation, but am struggling to figure out how to get this to work.

Ideally, my controller would look something like this:

@RequestMapping(value="/someurl", method=RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public someMethod(@Valid @ModelAttribute Order order, @RequestParam String parm1, @RequestParam String parm2) {

}

I need to post the form parameters to the controller URL along with some query parameters and a Content-Type = application/x-www-form-urlencoded

Any ideas on how to get this to work?

javaguy
  • 1
  • 3

1 Answers1

0

Suppose the Order class has the order_id and order_x attributes, with the following endpoint:

@RequestMapping(value="/someurl", method=RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public someMethod(@Valid @ModelAttribute Order order, BindingResult validation,  @RequestParam String parm1, @RequestParam String parm2) {

}

If a client sends a POST request with application/x-www-form-urlencoded content type with following request body:

order_id=1&order_x=something&parm1=foo&parm2=bar

then an Order instance with {order_id=1, order_x=something} will be instantiated. In addition, parm1 and parm2 will contain foo and bar, respectively. BindingResult contains validation results for a preceding command or form object (the immediately preceding method argument). See this discussion about Query Parameters in POST requests. Also Forms Spec is a good reference.

Community
  • 1
  • 1
Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
  • This doesn't really work. If I take off the @Valid annotation, it makes it into the method, but it doesn't map things correctly. The request parameters are mapped OK, but I lose the form values. – javaguy Aug 07 '15 at 12:32