servlet过滤器如何在Spring中运行?

时间:2015-02-03 07:34:05

标签: java spring spring-mvc servlets

我试图在我的Spring Web应用程序中添加CORS过滤器,但过滤器没有被执行。我已按照此处的相关步骤进行操作:https://spring.io/guides/gs/rest-service-cors/无济于事。我没有使用Spring Boot。我在3.0+ servlet规范容器中使用Spring的WebApplicationInitializer引导我的应用程序。

我的应用程序中的其他所有内容都在工作:配置类,控制器,休眠实体等。

更新1:

以下答案通过将过滤器添加到servlet容器来为我工作:

container.addFilter("CorsFilter", CorsFilter.class)
          .addMappingForUrlPatterns(null, false, "/*");

但是,我很好奇为什么Spring Boot不需要这个?他们必须自动搜索过滤器并将其添加到上下文中。有一种直截了当的方法吗?我不得不创建一个过滤器,然后将其添加到另一个类的某个列表中,这似乎很不幸。如果它们像Spring Boot一样自动注册,那就太好了。

相关代码段:

WebApplicationInitializer:

public class AppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) throws ServletException {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext =
                new AnnotationConfigWebApplicationContext();
        rootContext.register(AppConfig.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("/");
    }

}

的AppConfig:

@Configuration
@ComponentScan
public class AppConfig {
}

WebAppConfig:

@Configuration
@EnableWebMvc
@EnableSpringDataWebSupport
@ComponentScan(basePackageClasses = AppConfig.class)
public class WebAppConfig extends WebMvcConfigurerAdapter {
}

CorsFilter:

@Component
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String origin = httpRequest.getHeader("Origin");
        if (StringUtils.hasText(origin)) {

            boolean isMyDomain =
                Pattern.compile("^https://(.*?\\.)?mydomain.com(:\\d+)?$")
                        .matcher(origin)
                        .find();
            if (isMyDomain) {
                httpResponse.setHeader("Access-Control-Allow-Origin", origin);
            } else {
                httpResponse.setHeader("Access-Control-Allow-Origin", "mydomain");
            }

        }
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LoggerFactory.getLogger(getClass()).info("CorsFilter initiated");
    }

    @Override
    public void destroy() {
        LoggerFactory.getLogger(getClass()).info("CorsFilter destroyed");
    }
}

2 个答案:

答案 0 :(得分:1)

您可以这样添加:

container.addFilter("CorsFilter", CorsFilter.class)
          .addMappingForUrlPatterns(null, false, "/*");

答案 1 :(得分:1)

您必须在AppInitializer

中注册过滤器
public class AppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) throws ServletException {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext =
                new AnnotationConfigWebApplicationContext();
        rootContext.register(AppConfig.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("/");

        //Added filter dynamically
        javax.servlet.FilterRegistration.Dynamic corsFilter = container.addFilter("corsfilter", CORSFilter.class);
        corsFilter.addMappingForUrlPatterns(null, true, "/*");
    }

}

您可以参考this github repository