I have a GET method
@RequestMapping(
value = "/path/{field}",
method = RequestMethod.GET
)
public void get(@PathVariable String field) {
}
Field can contain slashes, like "some/thing/else" which results in the path not being found. It could even be something like "//////////////". Some examples:
www.something.com/path/field //works
www.something.com/path/some/thing
www.something.com/path///////////
I've tried with {field:.*} and escaping the slash with %2F but it still won't reach the method. Some help?
The addition of a slash at the end of a URL instructs the web server to search for a directory. This speeds the web page loading because the server will retrieve the content of the web page without wasting time searching for the file.
Unfortunately, we soon find out that this returns a 404 if the PathVariable contains a slash. The slash character is the URI standard path delimiter, and all that goes after it counts as a new level in the path hierarchy. As expected, Spring follows this standard.
So if you have slashes in your title you need to find a way to encode and decode your title in the URL if your application cannot make the routing to the resource if the title contains a slash. You could e.g. replace slahes with double hyphens (--) or similar.
Solution 1. The backslash ( "\" ) character is a special escape character used to indicate other special characters such as new lines ( \n ), tabs ( \t ), or quotation marks ( \" ). If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string: "\\Tasks" or @"\Tasks" .
I've solved the problem, for Spring Boot. First you have to configure Spring to allow encoded slashes.
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
DefaultHttpFirewall firewall = new DefaultHttpFirewall();
firewall.setAllowUrlEncodedSlash(true);
return firewall;
}
@Override
public void configure(WebSecurity web) throws Exception {
web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
}
}
Then you need to allow it from the embedded tomcat:
public class Application extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
SpringApplication.run(Application.class, args);
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setUrlDecode(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}
Although this works, the best way to do it is to just use query parameters instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With