2

I would like to use URLs in a path variable using Spring. However, I cannot get the desired behavior without having to encode the URL twice in the client.

In order to describe the problem I will take as reference the spring rest service tutorial, I changed the greeting method to use a path variable as follows:

    @GetMapping("/greeting/{name}")
    public Greeting greeting(@PathVariable(value = "name") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }

If try to use the URL http://localhost:8080/greeting/test/slash I would get a HTTP 404 NOT_FOUND response. But if I try something like http://localhost:8080/greeting/test%2Fslash, I will get a 400 BAD_REQUEST response.

There is one answer in this question that suggests the use of the ALLOW_ENCODED_SLASH property, but it does not work. Like changing the property in the RestServiceApplication class.

System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");

Any suggestions?

Edu
  • 159
  • 1
  • 14
  • [Ralf's answer](https://stackoverflow.com/a/58303792/11748454) seems to address all three issues you'll be facing: Tomcat's security feature, Spring's security feature and Spring's URI path parsing (which decodes the URI before extracting the parameters). – Piotr P. Karwasz Oct 02 '21 at 07:03
  • Yes, I tried that answer and it works. thanks! – Edu Oct 05 '21 at 08:08

1 Answers1

-1

As Piotr pointed out, one of the answers works as I would expect.

  • Allows the encoded slash.
  • Does not expand the path variable so I do not get a 404 either.

The solution would be as follow

@SpringBootApplication
public class RestServiceApplication implements WebMvcConfigurer {

    public static void main(String[] args) {
        System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
        SpringApplication.run(RestServiceApplication.class, args);
    }

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setUrlDecode(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}
Edu
  • 159
  • 1
  • 14