How to add filter to spring mvc in java config? 1


In this post I show you how to add filter in two different kinds of spring based configurations.

Configuration by WebApplicationInitializer

package raphaelsolarski.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import raphaelsolarski.filter.MyFilter;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

public class MyWebAppInitializer implements WebApplicationInitializer {

   public void onStartup(ServletContext container) {
       //here I can set up any kind of spring context -> xml/java...
       AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
       appContext.scan("raphaelsolarski");
       ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext));
       registration.setLoadOnStartup(1);
       registration.addMapping("/");
       container.addFilter("My filter", MyFilter.class).addMappingForServletNames(null, false, "dispatcher");
       //or container.addFilter("My filter", MyFilter.class).addMappingForUrlPatterns(null, false, "/*");
   }

}

Configuration by AbstractAnnotationConfigDispatcherServletInitializer

package com.raphaelsolarski.config;

import com.raphaelsolarski.filter.MyFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;

public class MyDispatcher extends AbstractAnnotationConfigDispatcherServletInitializer{
   @Override
   protected Class<!--?-->[] getRootConfigClasses() {
       return null;
   }

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

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

   @Override
   protected Filter[] getServletFilters() {
       return new Filter[] { new MyFilter() };
   }
}

One thought on “How to add filter to spring mvc in java config?

Comments are closed.