简体   繁体   中英

How to map @RequestParam to object?

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

}

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

public class RestDTO {
   private int a;
   private String b;
   private String n;
}

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 ?

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) {

}

Approach :1 You need to change the method to POST and can receive the DTO object as parameter to the controller method as below. With GET method you cant achieve it as GET will not have body.

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String content( @RequestBody RestDto restDto) {
 ....
}

Approach:2 Or If you still wants to go with GET method then add a constructor to the RestDto as below

public RestDto {
    public RestDto(int a, String b, String n){
     this.a = a;
     this.b = b;
     this.n = n;
   }
}

And your in your controller call the constructor as below :

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

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