1

In a Spring ReST Controller class, there are three methods with identical @RequestParams, but different RequestMappings and behavior, like in the following (simplified) example:

@RequestMapping(method = GET, value = "/search")
    public MySearchResponse findAll(
            @RequestParam(required = false, value = "foo") String foo,
            @RequestParam(required = false, value = "bar") String bar,
            @RequestParam(required = false, value = "baz") Long baz,
            @RequestParam(required = false, value = "fooBar") Long fooBar
    ) { ...}

@RequestMapping(method = GET, value = "/export")
    public MyExportResponse exportAll(
            @RequestParam(required = false, value = "foo") String foo,
            @RequestParam(required = false, value = "bar") String bar,
            @RequestParam(required = false, value = "baz") Long baz,
            @RequestParam(required = false, value = "fooBar") Long fooBar
    ) { ...}

Is there a way to avoid code duplication concerning the @RequestParam's?

1
  • 1
    Use an object to bind to.
    – M. Deinum
    Commented Nov 7, 2016 at 13:54

2 Answers 2

1

Replace them with a single object.

static class MyParmeters {
    String foo;
    String bar;
    Long baz;
    Long fooBar;
}

@RequestMapping(method = GET, value = "/search")
public MySearchResponse findAll(MyParmeters params) { ... }

@RequestMapping(method = GET, value = "/export")
public MyExportResponse exportAll(MyParameters params) { ... }

See also How to bind @RequestParam to object in Spring MVC.

2
  • That seems to be quite a nice solution :-) Is there a way to conveniently check if the required-Constraint is fulfilled (in case there are @RequestParams with attribute required=true)
    – Mr.Radar
    Commented Nov 7, 2016 at 14:06
  • 1
    Spring MVC: How to perform validation?
    – OrangeDog
    Commented Nov 7, 2016 at 14:07
0

You can define parent type called MyResponse and then you can use ResponseEntity as shown below:

@RequestMapping(method = GET, value = "/searchOrExport")
public ResponseEntity<MyResponse> exportAll(@RequestParam(required = false, value = "foo") String foo,
            @RequestParam(required = false, value = "bar") String bar,
            @RequestParam(required = false, value = "baz") Long baz,
            @RequestParam(required = false, value = "fooBar") Long fooBar) {
      //code to handle search and Export
}

Bean class API shown below:

public abstract class MyResponse  {
    //any common properties add here
}


public class MySearchResponse implements MyResponse {
   //add MySearchResponse properties
}

public class MyExportResponse implements MyResponse {
   //add MyExportResponse properties
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.