I'm having in my Annotation driven Spring MVC Java web application runned on jetty web server (currently in maven jetty plugin).
I'm trying to do some AJAX support with one controller method returning just String help text. Resources are in UTF-8 encoding and so is the string, but my response from server comes with
content-encoding: text/plain;charset=ISO-8859-1
even when my browser sends
Accept-Charset windows-1250,utf-8;q=0.7,*;q=0.7
I'm using somehow default configuration of spring
I have found a hint to add this bean to the configuration, but I think it's just not used, because it says it does not support the encoding and a default one is used instead.
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
</bean>
My controller code is (note that this change of response type is not working for me):
@RequestMapping(value = "ajax/gethelp")
public @ResponseBody String handleGetHelp(Locale loc, String code, HttpServletResponse response) {
log.debug("Getting help for code: " + code);
response.setContentType("text/plain;charset=UTF-8");
String help = messageSource.getMessage(code, null, loc);
log.debug("Help is: " + help);
return help;
}
Simple declaration of the
StringHttpMessageConverter
bean is not enough, you need to inject it intoAnnotationMethodHandlerAdapter
: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
withBeanPostProcessor
:-
Note that in Spring MVC 3.1 you can use the MVC namespace to configure message converters:
Or code-based configuration:
you can add produces = "text/plain;charset=UTF-8" to RequestMapping
see this blog for more detail
Just in case you can also set encoding by the following way:
I think using StringHttpMessageConverter is better than this.
if none of the above worked for you try to make ajax requests on "POST" not "GET" , that worked for me nicely ... none of the above did. I also have the characterEncodingFilter.
if you decide to fix this problem through the following configuration:
you should confirm that there should only one mvc:annotation-driven tag in all your *.xml file. otherwise, the configuration may not be effective.