views:

686

answers:

3

Hi,

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'?

Thanks Jon

+2  A: 

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

public String yourAction(HttpServletResponse response) {
    response.setContentType("application/json");
}
Bozho
Hi, I've tried that put I just get the error "cannot find symbolsymbol : class HttpServletResponse" when compiling
Ian morgan
well, did you import it? `import javax.servlet.http.HttpServeltResponse`
Bozho
and do you have the servlet-api on your classpath
Bozho
A: 

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?

Ichiro Furusato
+1  A: 

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 set the content-type to: 'application/json'.

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/view/json/MappingJacksonJsonView.html

Thomas Vanstals
Heh, I was doing manually what has already been provided for me by Spring. Thanks for the pointer :)
pHk