开发者

Spring - ModelAttribute and parameter names

How I can configure Model/Comm开发者_StackOverflow中文版and 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.


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;
    }
}


    @RequestMapping("/success")
    ModelAndView success(@RequestParam("sk_title") String title) {
       SomeCommand command = new SomeCommand();
       command.setTitle(title);
       model.addAttribute("title", command);
       //rest of code here
    }

class SomeCommand {
   String title
   public void setTitle(String title){
    this.title = title;
   }
}

You can make this more simple if you have control over the name attribute on the view. Simply change the name attributes to match the SomeCommand objects fields and spring will autobind them. How to bind request params in spring 3.0? You will still need to add the command to the model and this answer assumes you are using Spring 3 or greater. I assume spring may also require getters and setters on fields of the SomeCommand Object.

@RequestMapping
public ModelAndView success(SomeCommand someCommand) {
   model.addAttribute("someCommand", someCommand);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜