Saturday, August 08, 2015

CSV output with Spring

This is a simple way to respond with CSV output in Spring. I have used Spring REST here but this can be also done with Spring MVC etc


 Resource layer:

@RequestMapping(value="/{id}", method= RequestMethod.GET, produces = "text/csv")
    public ResponseEntity<String> getCsvDownload(final HttpServletResponse response, @NotNull @PathVariable("id") int id){
        response.setHeader("Content-Disposition", "attachment; filename=filename.csv");
        String csvResponse = applicationService.getCsv(id);
        return new ResponseEntity<>(csvResponse, HttpStatus.OK);

Service layer:

    public String getCsv(inal int id) {
      return StringUtils.join(applicationDao.getDetails(id), ",");