【问题标题】:Spring - slash character in GET URLSpring - GET URL中的斜杠字符
【发布时间】:2017-12-16 13:40:33
【问题描述】:

我有一个 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 转义斜线,但它仍然无法到达该方法。有什么帮助吗?

【问题讨论】:

  • 如果 field2 包含 /,则它不是同一个 url。这是预期的行为吗?
  • 不是,我的字段可以包含任意数量的斜线,甚至可以是“////////////”。
  • 我认为你必须处理/path1/**,然后自己解析整个路径。

标签: java spring spring-boot


【解决方案1】:

我已经解决了 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);
    }
}

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

【讨论】:

  • WebMvcConfigurerAdapter 现在似乎已被弃用
【解决方案2】:

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

@GetMapping("/path/**")
public String test(HttpServletRequest request) {
    return request.getRequestURI(); //do some kind of parsing
}

【讨论】:

  • 我给出的例子是一个简化,实际的 url 类似于:/path1/field1/path2/field2/path3/field3。在这种情况下,执行 /path1/** 似乎是一种 hack。
  • @AlexParvan 从你的问题来看,看起来你想要那个。否则,您将能够使用多个“@PathVariable”变量。
【解决方案3】:

我曾经遇到过这样的问题。看来我是通过以下方式解决的。

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

【讨论】:

  • 正如我所说,我尝试使用 {field:.*} 但我只得到 404,代码 String requestedField = URLDecoder.decode(field) 从未达到。
猜你喜欢
  • 2015-12-31
  • 1970-01-01
  • 1970-01-01
  • 2015-08-11
  • 2018-02-27
  • 2016-01-22
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多