1

I have a RESTful controller's method like:

 @RequestMapping(value = "", method = RequestMethod.GET,
        produces = {"application/json", "application/xml"})
@ResponseStatus(HttpStatus.OK)
public
@ResponseBody
Object getAll(@RequestParam(value = "1", required = false) Integer a,
              @RequestParam(value = "2", required = false) Integer b,
              @RequestParam(value = "2", required = false) String c,
              @RequestParam(value = "3", required = false) String d,
              @RequestParam(value = "4", required = false) String e,
              @RequestParam(value = "5", required = false) String f,
              @RequestParam(value = "6", required = false) String g,
              @RequestParam(value = "7", required = false) String h,
              HttpServletRequest request, HttpServletResponse response) {

    //some logic
    return service.getAll();
}

Is it possible to wrap all parameters to some Data Transfer Object? To a class like:

     public class ParamsDTO {

public String a;

public String b;

public String c;

//list of all params
}

Thus I can refactor my controller's methods like:

@RequestMapping(value = "", method = RequestMethod.GET,
        produces = {"application/json", "application/xml"})
@ResponseStatus(HttpStatus.OK)
public
@ResponseBody
Object getAll(@RequestBody ParamsDTO params,
              HttpServletRequest request, HttpServletResponse response) {

    //some logic
    return service.getAll();
}

I'm asking because I have about 10 different URL mappings with all these params and if I'm going to add new or remove old one I have to change it in 10 places. Is there a better way to achieve this? Thanks in advance.

Mikhail Kholodkov
  • 23,642
  • 17
  • 61
  • 78
  • 1
    http://stackoverflow.com/questions/16942193/spring-mvc-complex-object-as-get-requestparam duplicate? – hahn Feb 17 '16 at 19:37
  • you should use a command object (or call it a dto), the only thing you neet to take care of is, that you have `String get1()` and `void set1(String value)` but your fields name must not be a single number, but `value1` for example. – Ralph Feb 17 '16 at 19:54
  • Thanks hahn. It helps. Sorry for duplicate. – Mikhail Kholodkov Feb 17 '16 at 19:59

0 Answers0