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 " />
I found solution for Spring 3.1. with using @ResponseBody annotation. Here is example of controller using Json output:
@RequestMapping(value = "/getDealers", method = RequestMethod.GET,
produces = "application/json; charset=utf-8")
@ResponseBody
public String sendMobileData() {
}