DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • Building Resilient Identity Systems: Lessons from Securing Billions of Authentication Requests
  • Modern Test Automation With AI (LLM) and Playwright MCP
  • AI-Driven Test Automation Techniques for Multimodal Systems
  • How to Convert XLS to XLSX in Java
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring MVC: HTTP Message Converter

Spring MVC: HTTP Message Converter

Learn more about Spring MVC and the HTTP message converter.

By 
Michal Jastak user avatar
Michal Jastak
·
Oct. 18, 19 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
17.1K Views

Join the DZone community and get the full member experience.

Join For Free

Http message converter pigeons

Don't shoot the messenger (pigeons)!

Quite often, you need to provide users with the same data, but in different forms, like JSON, PDF, XLS, etc. If your application is Spring Framework-based, this task can be achieved using HTTP message converters.

HTTP message converters are applied when an HTTP request (or its parts) needs to be converted into type required for handler method argument (for more info, see Handler methods — method arguments), or when the value is returned by handler method needs to be converted somehow to create HTTP response (for more info, see Handler methods — Return values).

You may also like: How Spring MVC Really Works

The Spring Framework provides you with a set of predefined HTTP message converters. For example, for byte arrays, JSON, etc., this set can be modified or extended to best suit your needs.

In this post, we will focus on converting the value returned from the handler method into the desired form, using an example provided by myself a bit later on (see the link below to view the source code repository).

Suppose that we have a controller returning some Team data, like this (yes, I know, I've ignored teamId):

@RestController
public class TeamDetailsController {

    @GetMapping("/teams/{teamId}/")
    public Team read() {
        final Set<TeamMember> members = new LinkedHashSet<>();
        members.add(new TeamMember("Albert Einstein", LocalDate.of(1879, 3, 14)));
        members.add(new TeamMember("Benjamin Franklin", LocalDate.of(1706, 1, 17)));
        members.add(new TeamMember("Isaac Newton", LocalDate.of(1643, 1, 4)));
        return new Team(members);
    }

}


In our example, the handler method response will be, by default, converted into JSON:

{
  "members": [
    {
      "dateOfBirth": "1879-03-14",
      "name": "Albert Einstein"    },
    {
      "dateOfBirth": "1706-01-17",
      "name": "Benjamin Franklin"    },
    {
      "dateOfBirth": "1643-01-04",
      "name": "Isaac Newton"    }
  ]
}


If we would like to convert the data returned by the handler into XLS file, we can simply define a bean being HTTP message converter implementation, which will be activated by the HTTP Accept header:

@Service
public class TeamToXlsConverter extends AbstractHttpMessageConverter<Team> {

    private static final MediaType EXCEL_TYPE = MediaType.valueOf("application/vnd.ms-excel");

    TeamToXlsConverter() {
        super(EXCEL_TYPE);
    }

    @Override
    protected Team readInternal(final Class<? extends Team> clazz, final HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    protected boolean supports(final Class<?> clazz) {
        return (Team.class == clazz);
    }

    @Override
    protected void writeInternal(final Team team, final HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        try (final Workbook workbook = new HSSFWorkbook()) {
            final Sheet sheet = workbook.createSheet();
            int rowNo = 0;
            for (final TeamMember member : team.getMembers()) {
                final Row row = sheet.createRow(rowNo++);
                row.createCell(0)
                   .setCellValue(member.getName());
            }
            workbook.write(outputMessage.getBody());
        }
    }

}


You have to keep in mind that in our example, the defined HTTP message converter will always be applied when the handler method returns the value of type Team (see the supports method), and HTTP Accept header matches "application/vnd.ms-excel". In this case, the XLS file generated by the HTTP message converter is returned instead of the JSON representation of Team.

For more code, please check out my GitHub repo.

Further Reading

How Spring MVC Really Works

[DZone Refcard] Introduction to HTTP

Spring Framework

Published at DZone with permission of Michal Jastak, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!