Java spring framework - how to set content type?

I have a spring action that I rendered some json from the controller, at the moment when it returns the content type 'text / plain; charset = ISO-8859-1 '.

How can I change this to "application / json"?

+6
java spring spring-mvc
source share
4 answers

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

 public String yourAction(HttpServletResponse response) { response.setContentType("application/json"); } 
+18
source share

Have you tried using MappingJacksonJsonView ?

Spring-MVC View, which displays JSON content by serializing the model for the current request using Jackson ObjectMapper.

It sets the content type: application/json .

+5
source share

Yes, but this only works if you capture the HttpServletResponse in the controller.

In Spring 3, we recommend that you avoid referencing anything in the servlet domain, storing things exclusively for our POJOs and annotations. Is there a way to do this without reference to the HttpServletResponse? Ie keeping clean?

+2
source share
  @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 extra X bytes or something else for the β€œcallback” part in case you want JSONP (request for json cross site).

+2
source share

All Articles