I'm running a Spring Boot 1.2.3 application with embedded Tomcat.
I'd like to inject a custom contextPath on every request, based on the first part of the URL.
Examples:
http://localhost:8080/foo
has by defaultcontextPath=""
and should getcontextPath="foo"
http://localhost:8080/foo/bar
has by defaultcontextPath=""
and should getcontextPath="foo"
(URLs without path should stay as is)
I tried to write a custom javax.servlet.Filter
with @Order(Ordered.HIGHEST_PRECEDENCE)
, but it seems like I'm missing something. Here's the code:
@Component @Order(Ordered.HIGHEST_PRECEDENCE)
public class MultiTenancyFilter implements Filter {
private final static Pattern pattern = Pattern.compile("^/(?<contextpath>[^/]+).*$");
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) request;
final String requestURI = req.getRequestURI();
Matcher matcher = pattern.matcher(requestURI);
if(matcher.matches()) {
chain.doFilter(new HttpServletRequestWrapper(req) {
@Override
public String getContextPath() {
return "/"+matcher.group("contextpath");
}
}, response);
}
}
@Override public void init(FilterConfig filterConfig) throws ServletException {}
@Override public void destroy() {}
}
This should simply take the String after the first /
and before (if any) the second /
and then use it as return value for getContextPath()
.
But Spring @Controller @RequestMapping and Spring Security's antMatchers("/")
does not seem to respect it. Both still work as if contextPath=""
.
How can I dynamically override the context path for each request?