Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Spring: need wildcard @RequestMapping to match everything BUT /images/* with access to raw URL

I'm new to Spring taking over existing code that uses @RequestMapping for various routes. However, due to complexities of a new feature request, it would be much easier to bypass the Spring routing mechanism to have a single wildcard action method that matches all possible URLs EXCEPT for the asset directories:

match these:

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

but NOT:

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

My various attempts either don't match at all or match but only capture a single word rather than the entire raw 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
}

(Various Google searches and Stackoverflow searches of "[spring] requestmapping wildcard" haven't helped so far.)

like image 986
Pete Alvin Avatar asked Oct 20 '22 02:10

Pete Alvin


1 Answers

I would recomment the first approach involving access to static resources.

1) Since typically images/css are static resources, one approach is:

You can make good use of the mvc:resources element to point to the location of resources with a specific public URL pattern. Enter following in spring config xml file:

<mvc:resources mapping="/images/**" location="/images/" />

2) Another approach to acheive this is:

<mvc:interceptors>
  <mvc:interceptor>
      <mvc:mapping path="/**"/>
      <exclude-mapping path="/images/**"/>
      <bean class="com.example.MyCustomInterceptor" />
  </mvc:interceptor>
</mvc:interceptors>

And the Java Configuration:

@Configuration
@EnableWebMvc
public class MyWebConfig extends WebMvcConfigurerAdapter 
{
  @Override
  public void addInterceptors(InterceptorRegistry registry) 
  {
    registry.addInterceptor(new MyCustomInterceptor())
            .addPathPatterns("/**")
            .excludePathPatterns("/images/**");
  }
}
like image 64
aces. Avatar answered Nov 02 '22 07:11

aces.