Spring - GET URL中的斜杠字符

Ale*_*van 5 java spring spring-boot

我有一个GET方法

@RequestMapping(
        value = "/path/{field}",
        method = RequestMethod.GET
)
public void get(@PathVariable String field) {
}
Run Code Online (Sandbox Code Playgroud)

字段可以包含斜杠,例如"some/thing/else",这会导致找不到路径.它甚至可能像"//////////////".一些例子:

www.something.com/path/field //works
www.something.com/path/some/thing
www.something.com/path///////////
Run Code Online (Sandbox Code Playgroud)

我尝试使用{field:.*}并使用%2F转义斜杠,但它仍然无法访问该方法.一些帮助?

Ale*_*van 7

对于Spring Boot,我已经解决了这个问题.首先,您必须配置Spring以允许编码的斜杠.

@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());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你需要从嵌入式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);
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然这有效,但最好的方法是使用查询参数.

  • `WebMvcConfigurerAdapter` 现在似乎已被弃用 (2认同)