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):