I have the following piece of code in my initializer:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Filter[] getServletFilters() {
DelegatingFilterProxy shiroFilter = new DelegatingFilterProxy("shiroFilter");
shiroFilter.setTargetFilterLifecycle(true);
return new Filter[]{new CorsFilter(),shiroFilter};
}
}
I want CorsFilter
to be executed before ShiroFilter
. However, the Spring documentation doesn't say that the order in which the filters are executed is determined by their order in the returned array.
If it is, can someone please clarify it? If not, can someone suggest how do I guarantee the execution order of filters?
Basically, there are 3 steps to create a filter: - Write a Java class that implements the Filter interface and override filter's life cycle methods. - Specify initialization parameters for the filter (optional). - Specify filter mapping, either to Java servlets or URL patterns.
The FilterRegistrationBean is, as the name implies, a bean used to provide configuration to register Filter instances. It can be used to provide things like URL mappings etc.
Just to keep the question up to date.
Use the spring @Order - Annotation
@Component(value = "myCorsFilter")
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
[...]
}
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfiguration.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Filter[] getServletFilters() {
return new Filter[] {
new DelegatingFilterProxy("myEncodingFilter"),
new DelegatingFilterProxy("myCorsFilter"), // or just new CorsFilter()
new DelegatingFilterProxy("mySecurityFilter") //...
};
}
}
Filters are registered in the order of the array.
This results in ServletContext.addFilter()
being called in the order of items, however, I am not sure if this actually results in the filters being executed by the container in the order that they were registered.
Tomcat for example seems to use a HashMap to store filters so I wouldn't expect filters to necessarily run in the order that they were added.
Spring does provide a org.springframework.web.filter.CompositeFilter
, so I would simply return a single CompositeFilter
containing the two filters that you actually want to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With