通过使用url-mapping来定义ServletInitializer中的Filter

时间:2016-02-04 22:44:13

标签: spring spring-security servlet-filters

通过web.xml的旧样式:

<filter>
    <filter-name>accessFilter</filter-name>
    <filter-class>my.app.AccessFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>accessFilter</filter-name>
    <url-pattern>/admin/*</url-pattern>
</filter-mapping>

如何通过初始化器类实现相同的目标:

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    //...

    @Override
    protected Filter[] getServletFilters() { // nice. thx. url-mapping?
        return new Filter[]{ new AccessFilter() };
    }
}

1 个答案:

答案 0 :(得分:0)

你可以这样使用。

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
      FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("accessFilter", new AccessFilter());
      encodingFilter.addMappingForUrlPatterns(null, true, "/admin/*");

      super.onStartup(servletContext);
}