Spring - GET URL中的斜杠字符

时间:2017-07-12 08:29:39

标签: java spring spring-boot

我有一个GET方法

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

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

www.something.com/path/field //works
www.something.com/path/some/thing
www.something.com/path///////////

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

3 个答案:

答案 0 :(得分: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());
    }
}

然后你需要从嵌入式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);
    }
}

虽然这样可行,但最好的方法是使用查询参数。

答案 1 :(得分:1)

我有时会遇到这样的问题。看起来我用以下方式解决了它。

@RequestMapping(value = "/{field:.*}")
...
String requestedField = URLDecoder.decode(field)

答案 2 :(得分:1)

正如JeremyGrand建议您可以使用DeviceControlActivity匹配路由,然后自己解析路径:

this (return unable to add window token null error during run time)

DeviceControlActivity.this (won't compile, saying class is non-closing)

DeviceControlActivity.getapplication()

DeviceControlActivity.getapplication().this