Close

Spring MVC - HandlerMapping setDefaultHandler() Example

[Last Updated: Mar 7, 2018]

In this example, we will understand how HandlerMapping works with setting AbstractHandlerMapping.setDefaultHandler(....).

A default handler is used for all URIs requests which are not matched by any other handlers.

Initially all HandlerMappings' default handler is set to null. In order to make default handler working, we have to set it to an object of the type which the registered HandlerAdapters (one of them) can process.

Example

We are customizing the default RequestMappingHandlerMapping in this example. We are setting the default handler as an object of type HttpRequestHandler.

@Configuration
@ComponentScan
public class AppConfig extends WebMvcConfigurationSupport {
  @Override
  @Bean
  public RequestMappingHandlerMapping requestMappingHandlerMapping() {
      RequestMappingHandlerMapping m = super.requestMappingHandlerMapping();
      m.setDefaultHandler(new MyDefaultHandler());
      return m;
  }
}

public class MyDefaultHandler implements HttpRequestHandler {
  
@Override
public void handleRequest (HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    writer.write("response from MyDefaultHandler, uri: "+request.getRequestURI());
}
}
@Controller
public class ExampleController {
  
  @RequestMapping("/example")
  @ResponseBody
  public String handle () {
      return "response from ExampleController";
  }
}

The above controller is not very necessary to demonstrate the default handler settings, but we are just using it to see the rest of our application is working as expected.

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

mvn tomcat7:run-war

Output

This shows that only /example is mapped to our ExampleController, the rest of the URIs will be forwarded to the default handler.

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 4.3.9.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.0.1 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Handler Mapping Default Handler Example Select All Download
  • handler-mapping-default-handler
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • AppConfig.java

    See Also