I have been researching how to perform URL rewrites on Tomcat 8 and keep running into the same two suggestions.
1) Use Tuckey URLRewriteFilter. 2) Run Apache on top of Tomcat to use mod_rewrite.
In regards to the former, URLRewriteFilter doesn't appear to have any documentation about how to configure in a Java format as opposed to XML. My Spring MVC application does not make use of a web.xml file - all configuration is done via Java classes - and so I'm not in a position to configure with XML.
Is there any way to configure in this way or are there any good alternatives other than trying to run Apache on top of Tomcat?
For example, is there a way to achieve this in Java as opposed to XML:
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
This is my WebApplicationInitializer class:
public class Initializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.register(RootConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext =
new AnnotationConfigWebApplicationContext();
dispatcherContext.register(WebAppConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
dispatcher.addMapping("*.html");
}
}
My RootConfig
@Configuration
@ComponentScan(basePackages={"com.ucrisko.*"},
excludeFilters={
@ComponentScan.Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)
})
public class RootConfig {
}
And my WebAppConfig
@Configuration
@EnableWebMvc
@ComponentScan(basePackages={"com.ucrisko.*"})
public class WebAppConfig extends WebMvcConfigurerAdapter{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
...various other beans
}