【问题标题】:Spring MVC 3 Return Content-Type: text/plainSpring MVC 3 返回内容类型:文本/纯文本
【发布时间】:2012-02-15 14:47:11
【问题描述】:

我想在页面上显示简单的文本,因此我想将Content-Type 返回为text/plain

使用下面的代码,我在页​​面上看到纯文本,但返回 Content-Type 仍然是 text/html

我该如何解决这个问题?

注意:我在 Spring MVC 中使用 Tiles。返回的“m.health”指向映射到仅包含以下 1 行的 health.jsp 的切片 def。

更新说明:我无法控制 HTTP 标头请求中的 Content-TypeAccept 值。无论收到什么样的请求,我都希望我的回复返回text/plain

控制器:

@RequestMapping(value = "/m/health", method = RequestMethod.GET, headers = "Accept=*")
public String runHealthCheck(HttpServletResponse response, HttpServletRequest request, Model model) throws Exception {
    model = executeCheck(request, response, TEMPLATE, false, model);
    model.addAttribute("accept", "text/plain");
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    return "m.health";
}

JSP:

${状态}

【问题讨论】:

    标签: java spring-mvc content-type apache-tiles


    【解决方案1】:

    如果您使用 @ResponseBody 额外注释您的方法,它应该可以工作:

    @RequestMapping(value = "/",
                    method = RequestMethod.GET)
    @ResponseBody
    public String plaintext(HttpServletResponse response) {
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        return "TEXT";
    }
    

    【讨论】:

    • 对于任何访问此问题的人,马库斯在阿里接受后添加了他的回复,但这是使用注释时的正确方法。它很简单,效果很好。
    • 它不起作用。如果你使用@ResponseBody,Spring会用“application/json”重写Content Type
    • 这对我也不起作用。对我来说,它仍然以“text/html”的形式出现。
    • 对我不起作用。我收到 404 错误(其中包含返回的字符串。)
    • 对于其他人在这里回复它不起作用,这是正确的方法,并且将在 默认 下工作。 Review the documentation on the StringHttpMessageConverter 了解更多信息。
    【解决方案2】:

    您可以尝试使用text/plain 设置@RequestMapping 注释的produces 值。 Spring 文档将其列为sample

    【讨论】:

    • 我无法控制Content-Typerequest 中设置的内容,如果请求类型不是我在其中设置的,则生成的内容将不匹配。无论请求类型是什么,我基本上都想返回text/plain
    猜你喜欢
    • 2016-07-13
    • 1970-01-01
    • 2016-06-02
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 2016-09-27
    相关资源
    最近更新 更多