Spring MVC 3 Return Content-Type: text/plain

2019-01-17 21:25发布

I want to display simple text on a page and as such I want to return the Content-Type as text/plain.

Using the code below, I see plain text on the page, however the return Content-Type is still text/html.

How can I fix this?

NOTE: I'm using Tiles with Spring MVC. The returned "m.health" points to a tiles def that maps to a health.jsp which only contains the 1 line below.

UPDATE NOTE: I have no control over the Content-Type or Accept values in the HTTP Header request. I want my response to return text/plain no matter what kind of request comes in.

Controller:

@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:

${status}

2条回答
再贱就再见
2楼-- · 2019-01-17 22:03

It should work if you annotate your method additionally with @ResponseBody:

@RequestMapping(value = "/",
                method = RequestMethod.GET)
@ResponseBody
public String plaintext(HttpServletResponse response) {
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    return "TEXT";
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-17 22:25

You could try to set the produces value of your @RequestMapping annotation with text/plain. The Spring documentation lists this as a sample.

查看更多
登录 后发表回答