Spring-GET URL中的斜线字符 [英] Spring - slash character in GET URL

查看:357
本文介绍了Spring-GET URL中的斜线字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个GET方法

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

字段可以包含斜杠,例如"some/thing/else",这将导致找不到路径.甚至可能是"//////////////"之类的东西.一些例子:

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///////////

我已经尝试过使用{field:.*}并使用%2F转义斜线,但是仍然无法达到该方法.有帮助吗?

I've tried with {field:.*} and escaping the slash with %2F but it still won't reach the method. Some help?

推荐答案

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

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());
    }
}

然后您需要从嵌入式tomcat中允许它:

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.

这篇关于Spring-GET URL中的斜线字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆