The post request to my controller action is coming from ajax like this:
$.post("myurl.htm", { view: $("#selView").val(),
val1: "value1", val2: "value2"
});
I have two Models Foo and Bar
public class Foo {
public String val1;
//getter/setters
}
public class Bar {
public String val2;
//getters/setters
}
Now, my controller action looks like this:
@RequestMapping(value="/myurl.htm", method=RequestMethod.POST)
public ModelAndView doSomething (
@RequestParam(value="view", required=true) String view,
@RequestParam(value="val1", required=false) String val1,
@RequestParam(value="val2", required=false) String val2) {
Foo foo = new Foo();
Bar bar = new Bar();
if (view.equalsIgnoreCase("something"))
foo.setVal1(val1);
else if (view.equalsIgnoreCase("somethingelse"))
foo.setVal2(val2);
fooService.doSomeStuffWithDb(foo);
barService.doSomeStuffWithDb(bar);
}
Questions
-
Even though, everything above works I think there should be a better way to do this…? What if I had 10 parameteres posting in my post request, would I have 10 parameters in my controller action?? This would not scale well.
-
So, is there a way that spring can automagically bind the parameters to there relevant getters/setters on the model?
spring can inject request parameters as a Map:
use your javascript unmodified. this is not as elegant as the
@ModelAttributeversion, but scales prety well with a lot of parameters.