简体   繁体   中英

Spring MVC controller parameters binding: replace parameters with POJO

I have a simple controller method with more than 7 parameters and would like to refactor it using a model object instead, ie to extract a parameter object:

@RequestMapping(value="/{one}")
public String controllerMethod(@PathVariable(value="one") String one, @RequestParam String two, ... @RequestBody body) {
...
}

I tried to extract an object with setters and getters and pathVariable and requestParameters are mapped by name. However I have troubles making the same for @RequestBody, it doesn't work for me even if I put @RequestBody into setter...

public class Parameters {
    private String one; // pathVariable
    private String two; // requestParameter
    private String body;// requestBody - always NULL!
    // other fields definition

    public setBody(@RequestBody String body) {this.body = body}
    //other setters/getters
}
  1. How to keep @RequestBody parameter in extracted POJO?
  2. Another question is how to control name of parameters, ie if parameter name differs from the field name in POJO, is there any annotation? This one doesn't work:
    public void setOne(@RequestParameter(value="o") String one) {this.one = one}
  3. How to mark the fields as required or give a default value like in the @RequestParameter annotation?

For the (1) I would simply keep @RequestBody as a separate parameter though I don't like it much.

Ok, looks like the only way of doing (2) and (3) is through customizing data binding: the similar question

Feel free to post another easy solution if you know about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM