8

I'm writing a spring rest method to get details from database and set it in a response POJO and then return it. Currently I need to produce this response in CSV instead of default json when the URL is hit using POSTMAN or RC like a downloadable CSV file with data. I googled many sites but am not sure of few logics.

  1. Do we need to write business logic to convert pojo class values to csv format or does spring has any conversion mechanism ?
  2. Produces = "text/csv" is being mentioned on many places, does this convert response properly ?

Currently I haven't written any code for CSV conversion.

@GetMapping("/batch/export" , produces="text/csv")
public ResponseEntity<ApplicationResponse> getBatchDetails(
        HttpServletRequest request) {

    ApplicationRequest appRequest = ApplicationServiceMapper.mapRequestFromHttpRequest(request);
    ApplicationResponse response = appService.getDBDetails(appRequest);
    return new ResponseEntity<>(response, HttpStatus.OK);

}

Here response is the one that service returns with all the data in its pojo format and if we do not give produces in annotation then by default spring will return response json. Can someone guide me? Thanks in advance.

user2632905
  • 237
  • 2
  • 3
  • 12
  • Possible duplicate of [How to Return CSV Data in Browser From Spring Controller](https://stackoverflow.com/questions/22947751/how-to-return-csv-data-in-browser-from-spring-controller) – Krzysztof Cichocki Aug 17 '17 at 07:59
  • Spring Boot uses Spring WebMVC under the covers and Spring WebMVC has [built-in support](https://docs.spring.io/spring/docs/current/spring-framework-reference/html/view.html#view-jasper-reports) for CSV through JasperReports. Alternatively, a custom `MessageConverter` [can be built](https://stackoverflow.com/a/44094437/1126526) using any of the popular CSV handling libraries. – manish Aug 17 '17 at 08:02

1 Answers1

6

Just using the @GetMapping with produces="text/csv" is not enough. It is only responsible for setting the response header Content-Type: text/csv.

You'll need to add the response as a parameter HttpServletResponse response, convert your POJO into a valid csv file, and only then, write the csv file into the HttpServletResponse.

Pedro Tavares
  • 1,119
  • 8
  • 19