Tuckey URL重写过滤器Java类配置 [英] Tuckey URL Rewrite Filter Java Class Configuration

查看:128
本文介绍了Tuckey URL重写过滤器Java类配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究如何在Tomcat 8上执行URL重写,并不断遇到相同的两个建议.

I have been researching how to perform URL rewrites on Tomcat 8 and keep running into the same two suggestions.

1)使用Tuckey URLRewriteFilter. 2)在Tomcat上运行Apache以使用mod_rewrite.

1) Use Tuckey URLRewriteFilter. 2) Run Apache on top of Tomcat to use mod_rewrite.

关于前者,URLRewriteFilter似乎没有关于如何以Java格式而不是XML进行配置的任何文档.我的Spring MVC应用程序不使用web.xml文件-所有配置都是通过Java类完成的-因此我无法使用XML进行配置.

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.

除了试图在Tomcat上运行Apache之外,是否有任何其他方法可以配置?

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?

例如,有一种方法可以用Java而不是XML来实现:

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>

这是我的WebApplicationInitializer类:

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");
} 

}

我的RootConfig

My RootConfig

@Configuration
@ComponentScan(basePackages={"com.ucrisko.*"},
    excludeFilters={
      @ComponentScan.Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)
    })
public class RootConfig {

}

还有我的WebAppConfig

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
}

推荐答案

在Spring Boot中,您只需在配置中将filter定义为bean. 我不确定这是否可以在普通的Spring MVC中使用,但是您可以尝试.一件尴尬的事情是从Java代码配置过滤器-您将必须实现FilterConfig.一个有效的Spring Boot示例如下(来自config类的片段):

In Spring Boot you can just define filter as a bean in your configuration. I'm not sure if that works in plain Spring MVC but you can try. One awkward thing is configuring the filter from java code - you will have to implement FilterConfig. A working Spring Boot example looks like this (snippet from the config class):

@Bean
public UrlRewriteFilter urlRewriteFilter(final ServletContext servletContext) throws ServletException {
    UrlRewriteFilter urlRewriteFilter = new UrlRewriteFilter();
    urlRewriteFilter.init(new FilterConfig() {
        private final Map<String, String> params = new HashMap<String, String>();
        {
            params.put("confPath", "urlrewrite.xml");
        }

        @Override
        public String getFilterName() {
            return "UrlReriteFilter";
        }

        @Override
        public ServletContext getServletContext() {
            return servletContext;
        }

        @Override
        public String getInitParameter(String name) {
            return params.get(name);
        }

        @Override
        public Enumeration<String> getInitParameterNames() {
            return Collections.enumeration(params.keySet());
        }
    });

    return urlRewriteFilter;
}

对于常规的Spring MVC,似乎您应该实现WebApplicationInitializer. WebApplicationInitializer是与web.xml配置等效的Java代码.根据文档,Spring应该从类路径中获取实现并运行它们.示例实现可能如下所示(注意:我还没有测试过是否可行,但是应该将您设置在正确的路径上):

As for regular Spring MVC, it seems you should implement WebApplicationInitializer. WebApplicationInitializer is java code equivalent of web.xml configuration. According to documentation, Spring should pick up the implementations from the classpath and run them. Sample implementation may look like this (Note: I haven't tested if this works, but it should set you on the right path):

public class Initalizer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] {WebAppConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {"/*", "*.html"};
    }

    @Override
    protected Filter[] getServletFilters() {
        UrlRewriteFilter urlRewriteFilter = new UrlRewriteFilter();
        /*
         * Add filter configuration here if necessary
         */
        return new Filter[] {urlRewriteFilter};
    }
}

AbstractAnnotationConfigDispatcherServletInitializer是Spring的WebApplicationInitializer接口实现,旨在简化DispcherServlet的初始化(这是Spring MVC的入口点).在此示例中,WebAppConfig.class是您的主要Spring java配置类.

AbstractAnnotationConfigDispatcherServletInitializer is Spring's implementation of WebApplicationInitializer interface with intention to make initialization of DispcherServlet (which is entry point Spring MVC) easier. In this example WebAppConfig.class is your main Spring java config class.

编辑

如果您希望保留当前的初始化程序代码,也可以在onStartup方法中添加以下行:

If you prefer to keep your current initializer code, it should be also posssible to add following lines in onStartup method:

FilterRegistration.Dynamic urlRewriteFilter = servletContext.addFilter("urlRewriteFilter",  new UrlRewriteFilter());
urlRewriteFilter.setInitParameter("confPath", "urlrewrite.xml");
urlRewriteFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, "/*");

此摘录基于此处提供的答案:如何进行过滤器映射在AbstractAnnotationConfigDispatcherServletInitializer Spring中

This snipped is based on an answer available here: How to do filter mapping in AbstractAnnotationConfigDispatcherServletInitializer Spring

这篇关于Tuckey URL重写过滤器Java类配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆