1

I have a Spring controller mapping like following:

@RequestMapping(value = "api/{pathVar1}/receipt", method = RequestMethod.POST)
@ResponseBody
public String generateReceipt(HttpServletRequest request, @PathVariable String pathVar1) {
....
}

In this case what if the pathVar1 has slash('/'). Example request:

'api/CODE/1/receipt'

pathVar1 is supplied with

'CODE/1'

.

gpsingh
  • 11
  • 3
  • so what do you want pathVar1 to be actually? – Ken Chan Oct 21 '19 at 13:35
  • Want it to accept the value having slash. if I send this: 'api/CODE/1/receipt' API is not recognized because it was expecting 'api/CODE/receipt' two slashes only. – gpsingh Oct 21 '19 at 13:39

1 Answers1

0

I guess it's not the cleanest solution, but it seems to be working:

Replace @PathVariable in API path with ** to accept anything between "api/" and "/receipt", and then extract the needed part of path.

@RequestMapping(value = "api/**/receipt", method = RequestMethod.POST)
@ResponseBody
public String generateReceipt(HttpServletRequest request) {
    String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    String apiPath = new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    String neededPathVariableValue = apiPath.substring(0, apiPath.length() - "/receipt".length());

    //...
}
isank-a
  • 1,545
  • 2
  • 17
  • 22
htshame
  • 6,599
  • 5
  • 36
  • 56
  • thanks for the recommendation, I am checking this out. Let me know if there is any other alternative for this. – gpsingh Oct 22 '19 at 09:20