2

I'm creating a Rest api in Java with Spring and have urls such as

GET http://host:port/products/{resource}

The id's of resources are typically like version numbers such as 3.2 or a more elaborate example is x-light.5p.

Unfortunately, Spring seems to cut off the last part, thinking it is an extension (like .html or .png) so what actually enters my controller is not 3.2 but 3 and not x-light.5p but x-light. I experimented a bit and noticed that ending the request with an additional slash does work: GET http://host:port/products/x-light.5p/ does enter the controller in full.

For obvious reasons, changing our id's is a no go. Why is Spring behaving this way and can I change it? What would happen if I change my controller mapping from /products/{resource} to /products/{resource}/? Is this a way to enforce those who call the api to append the last slash? I thought the last slash was mostly redundant.

user1884155
  • 3,616
  • 4
  • 55
  • 108
  • It's confusing to ask a question about URLs with "dots" and obfuscate the hostname with `...`, you might want to change that. – Jim Garrison Feb 17 '18 at 00:28
  • 2
    Check this: https://stackoverflow.com/questions/16332092/spring-mvc-pathvariable-with-dot-is-getting-truncated – benji2505 Feb 17 '18 at 01:38

2 Answers2

1

User path mapping like this

{resource:.+}

@RequestMapping(method = RequestMethod.GET, value = "/products/{resource:.+}")
    public void myMthod(@PathVariable("id") String resource) {

    ....
    }
smruti ranjan
  • 741
  • 2
  • 9
  • 23
0

You can try the solution metioned in @benji2505 post or the below.

@RequestMapping(value = "/products/**", method = RequestMethod.GET)
public void products(HttpServletRequest request, HttpServletResponse response) {

    String pattern = (String)request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);  
    String resource = new AntPathMatcher().extractPathWithinPattern(pattern, request.getPathInfo());

}
Mahesh
  • 120
  • 9