在SpringBoot中返回动态txt(没有html)

时间:2018-03-20 14:22:55

标签: java spring spring-boot

我有一个应用程序,它接收一个文件作为输入,只返回一个字母作为输出(如A,B,C - 它是一个机器学习分类器,这些是类)。

我使用SpringBoot进行基本的应用程序设置,但我无法弄清楚除了作为完整HTML模板的一部分之外如何返回值。

这样可行,但这不是我想要的:

mytemplate.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{fragments/layout :: layout (~{::body},'hello')}">
<body>
<div class="container">
    <p th:text="${my_output}"/>
</div>
</body>
</html>

MyMainClass.java:

@RequestMapping("/my_test")
String my_test(Map<String, Object> model) {
    String result;
    ...processing...
    model.put("my_output", result);
    return "mytemplate";
}

我想要的只是返回一个字母,但是当我将mytemplate.html重命名为mytemplate.txt并且仅由${my_output}组成时,它只是将其作为文字字符串返回,而不是替换任何内容。基本上我需要一种方法来获取模板引擎以允许我生成这样的原始文本文件,或者我需要以某种方式绕过模板引擎。我对Spring Boot的工作方式或模板引擎一无所知,所以我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

尝试这样的事情

@RequestMapping("/my_test")
public String my_test(HttpServletResponse response) {
  String result;
  ...processing...
  response.setContentType("text/plain");
  response.setCharacterEncoding("UTF-8");
  return result ;
}