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. 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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.