1

In Spring web service, I have controller having multiple URL mapped method to handle requests. I want to map 2 urls to a single @GetMapping method like below:

@GetMapping(value = {"ex/{status}", "ex/retries/{status}"},  produces = "application/json")
public ResponseEntity<ResponsePOJO> getExRetries(@RequestParam("interval") Optional<String> intervalOptional, @PathVariable("status") String successStatus)
    {
/**
*LOTS OF WORK
*/

//If this method was called via ex/{status} then call using true
getReport(true);
//BUT if it was called via ex/retries/{status} then call using false i.e getReport(true);
}

Now based on through which of the 2 urls this method was invoked, only change would be that in the last line method call will be with true otherwise false. Now if I implement 2 methods for those 2 urls mapping and just change last line method call that would result in code duplication.

Is there a way to find which url was used to invoke it, then I can use if condition to make correct call and avoid 2 methods for it and hence code duplication.

nanosoft
  • 2,913
  • 4
  • 41
  • 61

2 Answers2

0

Add HttpServletRequest as an argument to the Controller method and than check the url.

  • Doesn't work - if I add a param in the method, result is 500 internal error : Failed to resolve argument 2 of type 'reactor.ipc.netty.http.server.HttpServerRequest' on public. If mentioned lines are added ServletRequestAttributes sra results in null giving NullPointerException. – nanosoft Jun 20 '18 at 09:23
  • Sorry I wrote wrong class it should be `HttpServletRequest`. Also are you working withing a servlet container? – Marcin Bukowiecki Jun 20 '18 at 10:06
  • Doesn't work either. infact this time it fails before going inside the method call itself. Mine is springboot application using webflux but I am using RestTemplate. – nanosoft Jul 02 '18 at 13:37
0

I think you should not overcomplicate it. You can have 2 methods which both call a third method that has a boolean parameter and contains Lots of work and getParameter(boolean param)

jarasez
  • 93
  • 9
  • This duplication of code bugs me. I am sure some other developer would have faced it earlier and solution would have been sought as well. And yes this shouldn't be complicated but simple 1-2 lines that it. – nanosoft Jun 20 '18 at 09:26