Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

java - Spring MVC 3 Return Content-Type: text/plain

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}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...