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")
    @ResponseBody
    public ResponseEntity<String> getCsvDownload(final HttpServletResponse response, @NotNull @PathVariable("id") int id){
        response.setHeader("Content-Disposition", "attachment; filename=filename.csv");
        response.setContentType("text/csv");
        String csvResponse = applicationService.getCsv(id);
        return new ResponseEntity<>(csvResponse, HttpStatus.OK);
    }


Service layer:

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