我一直在研究如何在Tomcat 8上执行URL重写,并不断遇到相同的两个建议。
1)使用Tuckey URLRewriteFilter。2)在Tomcat之上运行Apache以使用mod_rewrite。
关于前者,URLRewriteFilter似乎没有任何有关如何以Java格式而不是XML进行配置的文档。我的Spring
MVC应用程序不使用web.xml文件-所有配置都是通过Java类完成的,因此我无法使用XML进行配置。
除了尝试在Tomcat上运行Apache之外,是否有其他方法可以进行配置,或者有什么好的替代方法?
例如,有一种方法可以用Java而不是XML来实现:
UrlRewriteFilter
org.tuckey.web.filters.urlrewrite.UrlRewriteFilter
UrlRewriteFilter
/*
REQUEST
FORWARD
这是我的WebApplicationInitializer类:
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");
}
}
我的RootConfig
@Configuration
@ComponentScan(basePackages={"com.ucrisko.*"},
excludeFilters={
@ComponentScan.Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)
})
public class RootConfig {
}
还有我的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
}