Who sets response content-type in Spring MVC (@ResponseBody)
Simple declaration of the StringHttpMessageConverter
bean is not enough, you need to inject it into AnnotationMethodHandlerAdapter
:
<bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<array>
<bean class = "org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
</array>
</property>
</bean>
However, using this method you have to redefine all HttpMessageConverter
s, and also it doesn't work with <mvc:annotation-driven />
.
So, perhaps the most convenient but ugly method is to intercept instantiation of the AnnotationMethodHandlerAdapter
with BeanPostProcessor
:
public class EncodingPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String name)
throws BeansException {
if (bean instanceof AnnotationMethodHandlerAdapter) {
HttpMessageConverter<?>[] convs = ((AnnotationMethodHandlerAdapter) bean).getMessageConverters();
for (HttpMessageConverter<?> conv: convs) {
if (conv instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) conv).setSupportedMediaTypes(
Arrays.asList(new MediaType("text", "html",
Charset.forName("UTF-8"))));
}
}
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String name)
throws BeansException {
return bean;
}
}
-
<bean class = "EncodingPostProcessor " />
Responsebody encoding in Spring MVC 4.3.3
I find that I didn't add <value>application/json;charset=UTF-8</value>
in my configuration. I don't know why my old configuration works with version 4.2.7 and below, but this new configuration just works with version 4.3.3:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
</mvc:message-converters>
Content-type and @ResponseBody in spring
Submitted code produces text/html, as do all mapped Controller methods by default. If you want to produce application/json, you have to change your RequestMapping to
@RequestMapping(value="/foo", method=RequestMethod.GET, produces = "application/json")
However this is not a valid Json String, you would have to change it because the method you submitted would return empty body. The submitted example would be valid text/plain.
When the request contains header "Accept: application/json"
and other content type is returned, Spring returns Json-type response explaining that HttpMediaTypeNotAcceptableException
was thrown.
Regarding the servlet analogy - please explain, I don't fully understand what you mean. The String is returned as response body, it's very different from request attributes. What would you like to achieve?
Who sets request content-type in Spring MVC
I had a similar problem with JSON & Spring and solved the issue by specifying URIEncoding="UTF-8"
on <Connector>
in my Tomcat server.xml config, as described here:
http://wiki.apache.org/tomcat/FAQ/CharacterEncoding#Q8
Spring MVC 4: application/json Content Type is not being set correctly
First thing to understand is that the RequestMapping#produces()
element in
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
serves only to restrict the mapping for your request handlers. It does nothing else.
Then, given that your method has a return type of String
and is annotated with @ResponseBody
, the return value will be handled by StringHttpMessageConverter
which sets the Content-type
header to text/plain
. If you want to return a JSON string yourself and set the header to application/json
, use a return type of ResponseEntity
(get rid of @ResponseBody
) and add appropriate headers to it.
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> bar() {
final HttpHeaders httpHeaders= new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>("{\"test\": \"jsonResponseExample\"}", httpHeaders, HttpStatus.OK);
}
Note that you should probably have
<mvc:annotation-driven />
in your servlet context configuration to set up your MVC configuration with the most suitable defaults.
Java spring framework - how to set content type?
Pass the HttpServletResponse
to your action method and set the content type there:
public String yourAction(HttpServletResponse response) {
response.setContentType("application/json");
}
Multiple Content-type in Spring MVC
Yes, spring mvc request mapping supports multiple consumes MIME type , sample looks like
@RequestMapping(value = "/something", method = PUT, consumes = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE}, produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE})public SomeObject updateSomeObject(SomeObject acct) { return doStuff(acct);}
Related Topics
How to Scroll a Scrollview Programmatically in Android
Android Library Gradle Release Jar
How to Get a Context in a Recycler View Adapter
Recyclerview Item Click Listener the Right Way
Create a New Textview Programmatically Then Display It Below Another Textview
Delete Data from Arraylist with a For-Loop
Change Background Color of Single Specific Menu Items of Navigationview
Listview Is Blank While Using Getfilter Function
How to Generate Random Number in Specific Range in Android
Return a Value from Asynctask in Android
Sending a JSON Http Post Request from Android
How to Set Android Lock Screen Image
How to Get Specific Pushedid in Firebase
Findviewbyid Returns Null in a Dialog
Big-O Summary for Java Collections Framework Implementations