如何使用spring 3.0从@Responsebody注释中将响应作为.text文件

时间:2013-08-13 14:39:02

标签: spring-mvc

![在此处输入图片说明] [1]

任何人都可以解释一下如何使用spring 3.x实现此输出 当我点击一个按钮时,我想将数据提交到服务器,并使用@ResponseBody注释从spring controller 3.x获取文本(.txt)文件的响应......

3 个答案:

答案 0 :(得分:3)

尝试编写这样的@ResponseBody方法

@ResponseBody
@RequestMapping(value ="/txt" )
public String txtResponse(HttpServletResponse response){
    String fileName = "a.txt";
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    String content = "This is txt content";
    return content;
}

答案 1 :(得分:1)

这看起来非常类似于: Spring MVC 3 Return Content-Type: text/plainWho sets response content-type in Spring MVC (@ResponseBody)

您应该可以通过@RequestMapping设置响应的Content-Type标头:

@RequestMapping(..., produces = org.springframework.http.MediaType.TEXT_PLAIN)

这要求客户端传入Content-Type标头以匹配。

或者直接在服务方法的响应对象上设置标题,例如:https://stackoverflow.com/a/5268157/1546662

或者通过向spring上下文添加新的消息转换器,如:https://stackoverflow.com/a/3617594/1546662

中所述

答案 2 :(得分:0)

似乎有更好的解决方案

public ResponseEntity<Resource> exportTemplate() throws IOException {
    return ResponseEntity.ok().header("Content-Disposition", "inline;filename=" + "filename.txt")
            .body(new ByteArrayResource(new pojoObject()));
}