Spring MVC 3返回内容类型:text/plain

Ali*_*Ali 21 java content-type spring-mvc apache-tiles

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

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

我怎样才能解决这个问题?

注意:我正在使用带有Spring MVC的Tiles.返回的"m.health"指向一个tile def,它映射到一个health.jsp,它只包含下面的1行.

更新说明:我无法控制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";
}
Run Code Online (Sandbox Code Playgroud)

JSP:

$ {}状态

小智 53

如果您使用@ResponseBody另外注释您的方法,它应该有效:

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

  • 这是行不通的.如果您使用@ResponseBody,Spring将通过"application/json"重写内容类型 (8认同)
  • 对于访问此问题的任何人,Markus在Ali接受后添加了他的回复,但这是使用注释时的正确方法.它很简单,效果很好. (6认同)

Udo*_*eld 9

您可以尝试使用设置注释的produces值.Spring文档将此列为示例.@RequestMappingtext/plain