Close

Using Servlets and Filters in Spring MVC

[Last Updated: Jul 14, 2017]

There's no reasons, we cannot use Java Servlet components along with Spring MVC.

Spring MVC is itself based on Java Servlet (DispatcherServlet) and runs in a Servlet container.

We can register other Java Servlet components via web.xml or by using annotations

Let's see an example how to use a Servlet and a Filter in Spring MVC.

Example

A Spring Controller

@Controller
@RequestMapping("/app")
public class MyController {
  
  @RequestMapping
  @ResponseBody
  public String handleRequest () {
      System.out.println("-- handling request in controller --");
      return "dummy response from MyController";
  }
}

A Java Servlet

@WebServlet(name = "myServlet", urlPatterns = "/app2")
public class MyServlet extends HttpServlet {

  @Override
  protected void doGet (HttpServletRequest req,
                        HttpServletResponse resp)
            throws ServletException, IOException {
  
      System.out.println("-- In MyServlet --");
      PrintWriter writer = resp.getWriter();
      writer.println("dummy response from MyServlet");
  }
}

A Servlet Filter

@WebFilter(filterName = "myFilter", urlPatterns = "/*")
public class MyFilter implements Filter {
  
  @Override
  public void init (FilterConfig filterConfig) throws ServletException {
  }
  
  @Override
  public void doFilter (ServletRequest request, ServletResponse response,
                        FilterChain chain)
            throws IOException, ServletException {
      System.out.println("-- In MyFilter --");
      HttpServletRequest req = (HttpServletRequest) request;
      System.out.println("URI: " + req.getRequestURI());
      chain.doFilter(request, response);
  }
  
  @Override
  public void destroy () {
  }
}

Java Config class

@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig {
}

DispatcherServlet initializer

public class AppInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {
  
  @Override
  protected Class<?>[] getRootConfigClasses () {
      return null;
  }
  
  @Override
  protected Class<?>[] getServletConfigClasses () {
      return new Class<?>[]{MyWebConfig.class};
  }

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

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Accessing Spring Controller at /app

Output on server console:

-- In MyFilter --
URI: /app
-- handling request in controller --

Note that MyFilter is also working as expected.


Accessing Servlet at /app2

Output on server console:

-- In MyFilter --
URI: /app2
-- In MyServlet --

Other Options

Using HttpRequestHandler

An implementation of HttpRequestHandler can be thought as a mini Servlet which runs within Spring MVC's DispatcherServlet. See an example here.

Using Filter as Spring bean with DelegatingFilterProxy

See an example in the next tutorial.

Using Servlet components in Spring Boot

Check this tutorial out.

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 4.3.9.RELEASE: Spring Web MVC.
  • spring-test 4.3.9.RELEASE: Spring TestContext Framework.
  • javax.servlet-api 3.1.0 Java Servlet API
  • junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • JDK 1.8
  • Maven 3.3.9

Servlet Components in Spring MVC Example Select All Download
  • servlet-components-in-spring-mvc
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyServlet.java

    See Also