3

我正在尝试按照说明为 Spring Boot 配置预渲染过滤器,但由于 Boot 中没有 web.xml,我需要使用 Java 配置来执行此操作。

我试图遵循的带有 web.xml 的 Spring 应用程序的说明:

1:将此行添加到您的 web.xml:

<filter>
      <filter-name>prerender</filter-name>
      <filter-class>com.github.greengerong.PreRenderSEOFilter</filter-class>
      <init-param>
          <param-name>prerenderToken</param-name>
          <param-value>[get from prerender: https://prerender.io/]</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>prerender</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>

2:添加对你的项目pom的依赖:

<dependency>
  <groupId>com.github.greengerong</groupId>
  <artifactId>prerender-java</artifactId>
  <version>1.6.4-SNAPSHOT</version>
</dependency>

到目前为止我做了什么:

我将依赖项添加到 pom.xml 中。我创建了一个 WebConfig 类并实例化了 Bean:

@Configuration
public class WebConfig {
    @Bean
    public PreRenderSEOFilter PreRenderSEOFilter() {
        PreRenderSEOFilter prerenderFilter = new PreRenderSEOFilter();
        return prerenderFilter;
    }
}

但我不知道如何配置它。有prerenderFilter一个方法init(FilterConfig filterConfig)。但我不确定如何使用它。

如何配置此 prerenderFilter?

4

2 回答 2

4

在您的 WebApplicationInitializer 中,您可以使用以下代码:

    com.github.greengerong.PreRenderSEOFilter seoFilter = new com.github.greengerong.PreRenderSEOFilter();
    FilterRegistration.Dynamic filter =  container.addFilter("prerender", seoFilter);
    filter.setInitParameter("prerenderToken", "<YOU TOKEN>");
    filter.addMappingForUrlPatterns(null , true, "/*");
于 2015-07-13T20:58:22.230 回答
0

我想为 Aamirs 解决方案贡献 Spring Boot 版本。

@Configuration //instead of @SpringBootApplication 
@EnableAutoConfiguration //instead of @SpringBootApplication
@PropertySource(value = { "classpath:application.properties" })
@EntityScan("de.dpt.persistence")
@ComponentScan("de.dpt")
@EnableJpaRepositories("de.dpt.persistence")
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    @Override
    public void onStartup(ServletContext context) throws ServletException {

        PreRenderSEOFilter seoFilter = new PreRenderSEOFilter();
        FilterRegistration.Dynamic filter =  context.addFilter("prerender", seoFilter);
        filter.setInitParameter("prerenderToken", "<your token>");
        filter.addMappingForUrlPatterns(null , true, "/*");

        super.onStartup(context);
    }

}
于 2015-12-05T14:13:39.673 回答