gpt4 book ai didi

java - Spring - GET URL 中的斜杠字符

转载 作者:搜寻专家 更新时间:2023-10-31 08:31:44 25 4
gpt4 key购买 nike

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

最佳答案

我已经为 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);
}
}

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

关于java - Spring - GET URL 中的斜杠字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45052397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com