How I can configure Model/Command class to bind to specific request parameters?
For example i have following method:
@RequestMappint("/success")
ModelAndView success(@ModelAttribute SomeCommand command) {
// process
}
and command:
class SomeCommand {
String title
}
it's working fine for requests like /success?title=test
, when request params names equal to command properties names.
But what if I need to map some different name? for example if request like: /success?sk_title=test
.
How I can map request parameter sk_title
to title
field of my command?
This command have a bunch of params, and used by few different methods (it's an integration with other legacy system), so getting all this parameters as a @RequestParam for every RequestMapped method is a lot of work and requires too much copy/paste job, that brings a lot of bugs and unsupportable code.
I have no control on input parameters names, it have really weird names like 'sk_yt_saf_amount', it's why i'm trying to bind it to more friendly property names.
PS I'm using word 'command' there, as input data, to distinguish it from Model from ModelAndView conception.
@ModelAttribute is used for binding data from request param (in key value pairs), but @RequestBody is used for binding data from whole body of the request like POST,PUT.. request types which contains other format like json, xml.
@RequestParam is best for reading a small number of params. @ModelAttribute is used when you have a form with a large number of fields. @ModelAttribute gives you additional features such as data binding, validation and form prepopulation.
As described in the Spring MVC documentation - the @ModelAttribute annotation can be used on methods or on method arguments.
@ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute, and then exposes it to a web view. In this tutorial, we'll demonstrate the usability and functionality of this annotation through a common concept, a form submitted from a company's employee.
If you want map request parameter sk_title to title field, then add setter with name sk_title:
public class SomeCommand {
private String title;
public String getTitle() {
return title;
}
public void setSk_title(String title) {
this.title = title;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With