如何从Spring控制器返回浏览器中的CSV数据 [英] How to Return CSV Data in Browser From Spring Controller

查看:318
本文介绍了如何从Spring控制器返回浏览器中的CSV数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串中的CSV数据,并希望从Spring控制器返回它。想象数据看起来像这样

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

无论我尝试过什么,换行符都是'\\\
'在响应内容中,如果我双重转义它们,如在\\\
,响应只是包含双反斜杠。一般来说,如何在没有换行符的情况下返回带有换行符的纯文本数据?我知道如何返回纯文本,但仍然,内容带有转义换行...这是我目前有(使用Spring 3.0.5,而不是选择)

No matter what I have tried, the newlines come out as literally '\n' in the response content, and if I double escape them as in "\n", 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\n1,2,3\n3,4,5";
    return new ResponseEntity<>(data, responseHeaders, HttpStatus.OK);
}

其中产生字符串

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

在浏览器中。我们如何使它生产新的行在正确的数据,如上所示?

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

推荐答案

使用例如

@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");
}

因为返回类型是 void HttpServletResponse 声明为方法参数,当此方法返回时,请求被假定为完成。

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.

这篇关于如何从Spring控制器返回浏览器中的CSV数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆