Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

java - How to Return CSV Data in Browser From Spring Controller

Let say I have CSV data in a string and 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 have tried, the newlines come out as literally ' ' in the response content, and if I double escape them as in " ", the response just contains the double backslashes too. In general, how to I return plain text data with newlines in it without the newlines being modified? I know how to return plain text, but still, the content comes with escaped newlines... This is what I current have (using Spring 3.0.5, not by choice)

@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
1,2,3
3,4,5";
    return new ResponseEntity<>(data, responseHeaders, HttpStatus.OK);
}

Which produces literally the string

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

In the browser. How do I make it produce the correct data with new lines in tact as shown above?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could write to the response directly using e.g.

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

Since the return type is void and HttpServletResponse is declared as a method argument the request is assumed to be completed when this method returns.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...