Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - ModelAttribute and parameter names

Tags:

java

spring

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.

like image 383
Igor Artamonov Avatar asked Aug 30 '11 00:08

Igor Artamonov


People also ask

What is difference between @RequestBody and @ModelAttribute?

@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.

What is the difference between @RequestParam and @ModelAttribute?

@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.

Can we use ModelAttribute as a method argument?

As described in the Spring MVC documentation - the @ModelAttribute annotation can be used on methods or on method arguments.

What is ModelAttribute in spring?

@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.


1 Answers

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;
    }
}
like image 116
zoirs Avatar answered Oct 16 '22 14:10

zoirs