10

I have a spring action that I am rendering some json from the controller, at the minute its returning the content type 'text/plain;charset=ISO-8859-1'.

How can I change this to be 'application/json'?

1

4 Answers 4

19

Pass the HttpServletResponse to your action method and set the content type there:

public String yourAction(HttpServletResponse response) {
    response.setContentType("application/json");
}
3
  • Hi, I've tried that put I just get the error "cannot find symbol symbol : class HttpServletResponse" when compiling
    – Ian morgan
    Apr 9, 2010 at 8:40
  • 3
    well, did you import it? import javax.servlet.http.HttpServeltResponse
    – Bozho
    Apr 9, 2010 at 8:48
  • and do you have the servlet-api on your classpath
    – Bozho
    Apr 9, 2010 at 8:50
5

Did you try using the MappingJacksonJsonView?

Spring-MVC View that renders JSON content by serializing the model for the current request using Jackson's ObjectMapper.

It sets the content-type to: application/json.

1
  • Heh, I was doing manually what has already been provided for me by Spring. Thanks for the pointer :)
    – tmbrggmn
    Jul 17, 2010 at 18:39
3
 @RequestMapping(value = "jsonDemoDude", method = RequestMethod.GET)
    public void getCssForElasticSearchConfiguration(HttpServletResponse response) throws IOException {        
        String jsonContent= ...;
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(response);
        wrapper.setContentType("application/json;charset=UTF-8");
        wrapper.setHeader("Content-length", "" + jsonContent.getBytes().length);
        response.getWriter().print(jsonContent);
}

You can also add the aditional X bytes or whatever for "callback" part in case you want JSONP ( cross site json request ) .

2

Yes, but this only works if one is grabbing the HttpServletResponse in the controller.

In Spring 3 we're being encouraged to avoid references to anything in the servlet domain, keeping things solely to our POJOs and annotations. Is there a way to do this without referencing the HttpServletResponse? I.e., keeping ourselves pure?

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.