Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map @RequestParam to object?

Tags:

java

rest

spring

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public String content(
      @RequestParam int a,
      @RequestParam String b,
      ...
      @RequestParam String n;
) {

}

Can I somehow directly map all the @RequestParams into a java object, like?

public class RestDTO {
   private int a;
   private String b;
   private String n;
}
like image 285
membersound Avatar asked Jan 20 '15 08:01

membersound


2 Answers

In my opinon you have anything to do. The content method will be something like that :

public String content(@RequestParam RestDTO restDTO){...}

restDTO should have the correct setters. What happened when you do this ?

like image 140
vincent Avatar answered Sep 28 '22 10:09

vincent


If you encounter:

no matching editors or conversion strategy found

it may be because you are unnecessarily including @RequestParam in the controller method.

Make sure the attributes received as request parameters have getters and setters on the target object (in this case request parameters a, b, and n):

public class RestDTO {

    private int a;
    private String b;
    private String n;

    public int getA() {return a;}
    public void setA(int a) {this.a = a;}

    public int getB() {return b;}
    public void setB(int b) {this.b = b;}

    public int getC() {return c;}
    public void setC(int c) {this.c = c;}

}

Add the target object as a parameter in the controller method, but do not annotate with @RequestParam. The setter method of the target object will be called for each matching request parameter.

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public String content(RestDTO restDto) {

}
like image 23
Glenn Avatar answered Sep 28 '22 10:09

Glenn