Spring MVC - HandlerMapping setInterceptors() Example

[Updated: Dec 7, 2017, Created: Jul 5, 2017]

In this example, we will see how to set interceptors with a HandlerMapping by using method AbstractHandlerMapping#setInterceptors.


Creating an interceptor

public class MyInterceptor extends HandlerInterceptorAdapter {
  public boolean preHandle (HttpServletRequest request,
                            HttpServletResponse response,
                            Object handler) throws Exception {
      System.out.println("preHandle, URI: " + request.getRequestURI());
      return true;
  public void postHandle (HttpServletRequest request, HttpServletResponse response,
                          Object handler, ModelAndView modelAndView) throws Exception {
      System.out.println("postHandle, URI: " + request.getRequestURI());

Registering interceptor

In this example, we are going to use SimpleUrlHandlerMapping:

public class AppConfig {

  public SimpleUrlHandlerMapping simpleUrlHandlerMapping () {
      SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
      Map<String, Object> map = new HashMap<>();
      map.put("/app", httpRequestHandler());
      mapping.setInterceptors(new Object[]{new MyInterceptor()});
      return mapping;
  HttpRequestHandler httpRequestHandler () {
      return new MyHttpRequestHandler();

The handler

public class MyHttpRequestHandler implements HttpRequestHandler {
  public void handleRequest (HttpServletRequest request,
                             HttpServletResponse response)
            throws ServletException, IOException {
      System.out.println("handling request in MyHttpRequestHandler");
      PrintWriter writer = response.getWriter();
      writer.write("response from MyHttpRequestHandler, uri: " + request.getRequestURI());

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

mvn tomcat7:run-war


Output on the server console:

preHandle, URI: /app
handling request in MyHttpRequestHandler
postHandle, URI: /app

In the next tutorial, we will understand what is the difference between registering a HandlerInterceptor with HandlerMapping#setInterceptors() and with InterceptorRegistry#addInterceptor() (by extending WebMvcConfigurerAdapter).

Example Project

Dependencies and Technologies Used :

  • spring-webmvc 4.2.4.RELEASE: Spring Web MVC.
  • spring-test 4.2.4.RELEASE: Spring TestContext Framework.
  • javax.servlet-api 3.0.1 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

Handler Interceptors Example Project Select All Download
  • handler-interceptors-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also