Home » Java » Enterprise Java » Spring MVC – HTTP message converter

About Michal Jastak

Michal Jastak
Michał is a Chief Technology Officer in Java Division of AIS.PL, company developing mostly Web Applications of different kind, usually e-Government related.

Spring MVC – HTTP message converter

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 HTTP request (or its parts) needs to be converted into type required for handler method argument (see: Handler methods – method arguments), or when value returned by handler method needs to be converted somehow to create HTTP response (see: Handler methods – Return values).

Spring Framework provides you with a set of predefined HTTP message converters, for ex. for byte arrays, JSON, etc. – This set can be modified or extended to your needs.

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

 Suppose that we have a controller returning some Team data, like this (yes, I know, I’ve ignored team Id)

01
02
03
04
05
06
07
08
09
10
11
12
13
@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, handler method response will be, by default, converted into JSON:

01
02
03
04
05
06
07
08
09
10
11
12
13
{
  "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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@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, defined HTTP message converter will be applied always when the handler method returns value of type Team (see supports method), and HTTP Accept header matches “application/vnd.ms-excel”. In this case, XLS file generated by the HTTP message converter is returned instead of JSON representation of Team.

Few links for the dessert:

Published on Java Code Geeks with permission by Michal Jastak, partner at our JCG program. See the original article here: Spring MVC – HTTP message converter

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of