Java Spring:需要通配符@RequestMapping 来匹配所有内容,但 /images/* 可以访问原始 URL

Pet*_*vin 5 java spring spring-mvc

我是 Spring 的新手,接管了将 @RequestMapping 用于各种路由的现有代码。但是,由于新功能请求的复杂性,绕过 Spring 路由机制以使用单个通配符操作方法来匹配除资产目录之外的所有可能的 URL 会容易得多:

匹配这些:

(空)
//
anything/you/can/throw/at/it?a=b&c=d

但不是:

/images/arrow.gif
/css/project.css

我的各种尝试要么根本不匹配,要么匹配但只捕获一个单词而不是整个原始 URL:

@RequestMapping(value="{wildcard:^(?!.*(?:images|css)).*\$}", method=RequestMethod.GET)
public String index(@PathVariable("wildcard") String wildcard,
                    Model model) {
    log(wildcard); // => /anything/you/can/throw/at/it?a=b&c=d
}
Run Code Online (Sandbox Code Playgroud)

(到目前为止,“[spring] requestmapping 通配符”的各种 Google 搜索和 Stackoverflow 搜索都没有帮助。)

ace*_*es. 3

我会推荐第一种涉及访问静态资源的方法。

1)由于通常图像/css是静态资源,一种方法是:

您可以充分利用 mvc:resources 元素来指向具有特定公共 URL 模式的资源的位置。在 spring 配置 xml 文件中输入以下内容

<mvc:resources mapping="/images/**" location="/images/" />
Run Code Online (Sandbox Code Playgroud)

2)实现这一点的另一种方法是:

<mvc:interceptors>
  <mvc:interceptor>
      <mvc:mapping path="/**"/>
      <exclude-mapping path="/images/**"/>
      <bean class="com.example.MyCustomInterceptor" />
  </mvc:interceptor>
</mvc:interceptors>
Run Code Online (Sandbox Code Playgroud)

以及 Java 配置:

@Configuration
@EnableWebMvc
public class MyWebConfig extends WebMvcConfigurerAdapter 
{
  @Override
  public void addInterceptors(InterceptorRegistry registry) 
  {
    registry.addInterceptor(new MyCustomInterceptor())
            .addPathPatterns("/**")
            .excludePathPatterns("/images/**");
  }
}
Run Code Online (Sandbox Code Playgroud)