Mastering Spring’s HttpMessageConverter: Elegant Request/Response Handling
This article explains how Spring's HttpMessageConverter abstracts HTTP message conversion, shows how to read request bodies via HttpInputMessage and ServletServerHttpRequest, demonstrates a practical filter using FormHttpMessageConverter, and illustrates writing JSON responses with MappingJackson2HttpMessageConverter, all with concise code examples.
When working with Spring MVC, handling HttpServletRequest and HttpServletResponse directly can become cumbersome. A more elegant approach is to use Spring's HttpMessageConverter to read the request body and write the response.
HttpMessageConverter
HttpMessageConverteris a strategy interface provided by Spring for converting HTTP requests and responses. It reads from HttpInputMessage and writes to HttpOutputMessage. All message conversion in Spring MVC is performed through implementations of this interface.
Common implementations handle Form submissions, JSON, XML, plain strings, and even Protobuf. These converters are stored in a container HttpMessageConverters within the Spring IoC context.
HttpInputMessage
HttpInputMessagerepresents an HTTP input consisting of headers and a readable body, typically implemented by the server's request or the client's response.
ServletServerHttpRequest
ServletServerHttpRequestimplements HttpInputMessage and wraps an HttpServletRequest. By injecting the servlet request into this wrapper, HttpMessageConverter can process the original request data.
Practical Request Body Extraction
In a servlet filter we can use FormHttpMessageConverter (which handles application/x-www-form-urlencoded) to read the request body:
@Component
public class FormUrlencodedFilter implements Filter {
private final FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
private static final Logger log = LoggerFactory.getLogger(FormUrlencodedFilter.class);
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException {
String contentType = request.getContentType();
MediaType type = StringUtils.hasText(contentType) ? MediaType.valueOf(contentType) : null;
ServletServerHttpRequest serverHttpRequest = new ServletServerHttpRequest((HttpServletRequest) request);
if (formHttpMessageConverter.canRead(MultiValueMap.class, type)) {
MultiValueMap<String, String> read = formHttpMessageConverter.read(null, serverHttpRequest);
log.info("Read request body: {}", read);
}
}
}Sending a POST request with Content-Type: application/x-www-form-urlencoded such as:
POST /ind HTTP/1.1
Host: localhost:8080
Content-Type: application/x-www-form-urlencoded
Content-Length: 20
a=b123&c=d123&e=f123will produce a console log like:
Read request body: {a=[b123], c=[d123], e=[f123]}ServletServerHttpResponse
Similarly, ServletServerHttpResponse wraps HttpServletResponse. To write a JSON response we can use MappingJackson2HttpMessageConverter:
ServletServerHttpResponse servletServerHttpResponse = new ServletServerHttpResponse(response);
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
// authentication is the object to be serialized
mappingJackson2HttpMessageConverter.write(authentication, MediaType.APPLICATION_JSON, servletServerHttpResponse);Summary
HttpMessageConverterabstracts HTTP message conversion, allowing elegant handling of request and response data. Remember that the request body can be read only once, even when wrapped in ServletServerHttpRequest, and be aware of the difference between this wrapper and HttpServletRequestWrapper.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
