Spring MVC - Mapping a Controller implementation with SimpleControllerHandlerAdapter strategy

[Updated: Jun 26, 2017, Created: Jun 26, 2017]

This example demonstrates how to use an implementation of Controller interface. The implementation will be invoked by SimpleControllerHandlerAdapter (an HandlerAdapter strategy, registered by default). Also, we will map the requested URL to our Controller by using BeanNameUrlHandlerMapping (check out HandlerMapping tutorial).


Implementing Controller

public class MySimpleControllerHandler implements Controller {
  public ModelAndView handleRequest (HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {
      PrintWriter writer = response.getWriter();
      writer.write("response from MySimpleControllerHandler, uri: "
                             + request.getRequestURI());
      return null;

Mapping URL

Using BeanNameUrlHandlerMapping strategy:

public class AppConfig {
  @Bean(name = "/example")
  public Controller simpleControllerHandler () {
      return new MySimpleControllerHandler();

Note that BeanNameUrlHandlerMapping is registered by default when using @EnableMvc. All we have to do is to use bean name starting with a '/'; this name will be used as URI. Also our MySimpleControllerHandler#handleRequest will be invoked without any further configuration as corresponding SimpleControllerHandlerAdapter is registered by default as well.

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

mvn tomcat7:run-war


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

Simple Controller Handler Adapter Example Select All Download
  • simple-controller-handler-adapter-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also