Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do filter mapping in AbstractAnnotationConfigDispatcherServletInitializer Spring

Here is the problem: I can successfully register the Filter, but don't know how to set the mapping URL using this specific configuration.

Here is my Class:

public class WebInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

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

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

    @Override
    protected Filter[] getServletFilters() {

        return new Filter[]{
            new DelegatingFilterProxy("springSecurityFilterChain"),
            new DelegatingFilterProxy("customFilter")
        };
    }

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

P.D. I had done it using WebApplicationInitializer, but I want to use AbstractAnnotationConfigDispatcherServletInitializer.

like image 291
Charlires Avatar asked Aug 08 '14 17:08

Charlires


1 Answers

The only way I was able to do this was to use the FilterRegistration.Dynamic interface. In your WebInitializer class, add your custom filter manually in the onStartup method (an override from a superclass). There is no way that is more elegant at the moment to my knowledge.

@Override
public void onStartup(ServletContext servletContext)
        throws ServletException {
      FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("my-filter", new MyFilter());
      encodingFilter.setInitParameter("blah", "blah");
      encodingFilter.addMappingForUrlPatterns(null, false, "/toBeFiltered/*");

    super.onStartup(servletContext);
}

If you want this filter to work correctly then it would be best for you to comment out the getServletFilters method you have overridden so that this filter is served back correctly from the servletContext.

like image 97
dectarin Avatar answered Oct 19 '22 04:10

dectarin