How to return CSV data in browser from Spring Controller

Say I have CSV data in a row and you want to return it from a Spring controller. Imagine the data looks like this:

a,b,c 1,2,3 4,5,6 

No matter what I tried, the lines of the newline look literally "\ n" in the content of the response, and if I double them, as in "\ n", the answer simply contains double backslashes. In general, how can I return text data with new lines in it without changing new lines? I know how to return plain text, but nonetheless, the content comes with escaped newline characters ... This is what I have (using Spring 3.0.5, not optional)

 @RequestMapping(value = "/api/foo.csv") public ResponseEntity<String> fooAsCSV() { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("Content-Type", "text/plain; charset=utf-8"); String data = "a,b,c\n1,2,3\n3,4,5"; return new ResponseEntity<>(data, responseHeaders, HttpStatus.OK); } 

What literally produces a string

 "a,b,c\n1,2,3\n,3,4,5" 

In the browser. How to make it create the correct data with new lines in a measure as shown above?

+8
java spring spring-mvc csv
source share
2 answers

You can directly write an answer using, for example,

 @RequestMapping(value = "/api/foo.csv") public void fooAsCSV(HttpServletResponse response) { response.setContentType("text/plain; charset=utf-8"); response.getWriter().print("a,b,c\n1,2,3\n3,4,5"); } 

Since the return type is void and the HttpServletResponse declared as an argument to the method, it is assumed that the request is completed when this method returns.

+13
source share

Have you tried @ResponseBody in your controller method?

 @RequestMapping(value = "/api/foo.csv") @ResponseBody public String fooAsCSV(HttpServletResponse response) { response.setContentType("text/plain; charset=utf-8"); String data = "a,b,c\n1,2,3\n3,4,5"; return data; } 

Edit: Spring docs explain this here: http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

+2
source share

All Articles