Spring MVC: @RequestMapping: How to catch Map para

2019-09-18 02:25发布

问题:

I have the controller method for processing form submitting:

@RequestMapping(method = {RequestMethod.POST})
    public String submitForm(...){...}

But, I have got a new test case:

If Form has parameter ProductData call controller method submitFormWithProductData. and I am facing difficulties with this, because ProductData is a Map. On Site ProductData field in form tag looks like:

<input type="text" name="productData['param1']">
<input type="text" name="productData['param2']">

And I don't know, how to create right @RequestMapping annotation for submitFormWithProductData method.

I have tried:

@RequestMapping(method = {RequestMethod.POST}, params="productData")

and

@RequestMapping(method = {RequestMethod.POST}, params="productData[]")

but I didn't get success.

回答1:

productData has to be a property of a model object.

public class FormModel {
    private Map<String,String> productData = ...;
    ...
}

according to this you have to create a handler method like that:

@RequestMapping(....)
public String submitFormWithProductData(FormModel formModel) {
  ....
}

Spring will automatically bind the productData parameters to the according property in the FormModel object.

But I don't know why you want to handle it differently. You could add a hidden input field productDataSubmitted and add the following handler:

@RequestMapping(method = {RequestMethod.POST}, params="productDataSubmitted")


回答2:

Use @RequestBody Map<String,String> productData as argument int the controller method.

Here is a Blog and Read more...

For example:

@RequestMapping(value = "/add", method = RequestMethod.POST, consumes="application/json")
public void submitForm(@RequestBody Map<String,String> productData, Model model) {
    // implementation omitted
}