Close

Spring MVC - Using HttpRequestHandler with HttpRequestHandlerAdapter strategy

[Last Updated: Jun 26, 2017]

This example demonstrates how to use HttpRequestHandler by making use of HttpRequestHandlerAdapter (an HandlerAdapter strategy, registered by default). We will map the requested URL to our HttpRequestHandler by using BeanNameUrlHandlerMapping (check out HandlerMapping tutorial).

Example

Implementing HttpRequestHandler

public class MyHttpRequestHandler implements HttpRequestHandler {
  
  @Override
  public void handleRequest (HttpServletRequest request,
                             HttpServletResponse response) throws ServletException, IOException {
      PrintWriter writer = response.getWriter();
      writer.write("response from MyHttpRequestHandler, uri: "+request.getRequestURI());
  }
}

Mapping URL

Using BeanNameUrlHandlerMapping strategy:

@EnableWebMvc
@Configuration
public class AppConfig {

  @Bean(name = "/example")
  public HttpRequestHandler httpRequestHandler () {
      return new MyHttpRequestHandler();
  }
}

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 MyHttpRequestHandler#handleRequest will be invoked without any further configuration as corresponding HttpRequestHandlerAdapter is registered by default as well.

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

mvn tomcat7:run-war

Output

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

Spring Http Request Handler Example Select All Download
  • http-request-handler-adapter-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyHttpRequestHandler.java

    See Also