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
package com.logicbig.example;
import org.springframework.web.HttpRequestHandler;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
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:
package com.logicbig.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@EnableWebMvc
@Configuration
public class AppConfig {
@Bean(name = "/example")
public HttpRequestHandler httpRequestHandler () {
return new MyHttpRequestHandler();
}
}
Note that BeanNameUrlHandlerMapping is registered by default when using @EnableWebMvc. All we have to do is use a bean name that starts with a '/'; this name will then be used as the URI. Also, our MyHttpRequestHandler#handleRequest method will be invoked without any further configuration, as the corresponding HttpRequestHandlerAdapter is registered by default as well.
To try examples, run embedded Jetty (configured in pom.xml of example project below):
mvn jetty:run
Output
 $ curl -s "http://localhost:8080/example" response from MyHttpRequestHandler, uri: /example
Example ProjectDependencies and Technologies Used: - spring-webmvc 7.0.6 (Spring Web MVC)
Version Compatibility: 3.2.9.RELEASE - 7.0.6 Version compatibilities of spring-webmvc with this example: Versions in green have been tested.
- jakarta.servlet-api 6.1.0 (Jakarta Servlet API documentation)
- JDK 25
- Maven 3.9.11
|