Spring MVC 3 Return Content-Type: text/plain
Asked Answered
S

2

26

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}

Snailpaced answered 21/1, 2012 at 7:57 Comment(0)
M
58

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";
}
Merwyn answered 14/3, 2012 at 22:11 Comment(6)
For anyone visiting this question, Markus added his reply after Ali accepted, but this is the correct approach when using annotations. It is simple and works well.Eclecticism
It does not work. If you use @ResponseBody, Spring will rewrite Content Type by "application/json"Snowbird
This didn't work for me either. For me, it's still coming out as "text/html".Hemstitch
Doesn't work for me. I get a 404 error (which contains the returned string.)Vibrant
For anyone else replying here that it doesn't work, this IS the correct approach, and will work by default. Review the documentation on the StringHttpMessageConverter for more information.Eclecticism
I still have application/json type in response. I guess because i have Jackson in the classpath.Allocution
V
10

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

Vierno answered 21/1, 2012 at 8:11 Comment(1)
I have no control over what Content-Type is set in the request and produces will not match if the request type is not what I set in it. I basically want to return text/plain no matter what the request type is.Snailpaced

© 2022 - 2024 — McMap. All rights reserved.