lorraine batol
lorraine batol

Reputation: 6281

spring java based - adding of filter

in xml in order to add a cors filter, we would do something like this in web.xml:

  <filter>
    <filter-name>cors</filter-name>
    <filter-class>MyCorsFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/secured/*</url-pattern>
  </filter-mapping>

But we're on java based configuration now, how can we implement this programmatically?

Upvotes: 1

Views: 2107

Answers (1)

Ben Green
Ben Green

Reputation: 4121

If I am understanding you correctly, you are talking about java based spring configuration. We are also using Java based configuration, but are still using the web.xml. You have to add your Java configuration file as a context param in the web.xml like so:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.spring.AppConfig</param-value>
</context-param>

So, you can still add your filters as you did above.

Alternatively, if you are using the WebApplicationInitializer to configure the ServletContext, you can do the following:

public class WebAppInitializer implements WebApplicationInitializer {  

    @Override  
    public void onStartup(ServletContext container) throws ServletException {  
        container.addFilter("fooFilter", FooFilter.class); 
    }
}

EDIT: Answer to question in comment - Bearing in mind I have never done this before, but from looking at the docs for ServletContext and FilterRegistration, I would suggest trying this to get the filter mapped to a specific URL:

container.getFilterRegistration("fooFilter")
    .addMappingForUrlPatterns(DispatcherType.REQUEST, true, "/secured/");

Upvotes: 1

Related Questions