使@ResponseBody注释的Spring(Boot)MVC控制器方法返回UTF-8 [英] Make @ResponseBody-annotated Spring (Boot) MVC controller methods return UTF-8
问题描述
我正在使用Spring Boot构建Spring MVC服务,并希望能够以UTF-8编码的纯文本形式返回字符串.遵循此描述,我认为唯一必要的事情应该是添加bean方法
I'm building a Spring MVC service using Spring Boot and want to be able to return strings as plain text encoded in UTF-8. Following this description, I thought the only thing necessary should be to add the bean method
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", Charset.forName("UTF-8"))));
return converter;
}
但
中的root
方法
@Controller
public class RootController {
@RequestMapping(value="/"/*, produces="text/plain;charset=UTF-8"*/)
@ResponseBody
public String root() {
return "æøå";
}
}
响应ISO-8859-1中的字符串æøå
而不是UTF-8,除非我取消注释produces
部分,在这种情况下,它实际上返回UTF-8.消息转换器在这里似乎没有任何作用.
responds the string æøå
in ISO-8859-1 instead of UTF-8, unless I uncomment the produces
part, in which case it actually returns UTF-8. The message converter doesn't seems to have any effect here.
按照此方法,我确认该bean实际上已经被注册.除了这个bean,我还注册了EmbeddedServletContainerFactory
和CharacterEncodingFilter
,如
Following this approach I confirm that the bean has actually been registered. Besides this bean, I also register an EmbeddedServletContainerFactory
and CharacterEncodingFilter
as described in another question, although I don't think that's relevant here.
有人可以解释注册的HttpMessageConverter
的实际作用,以及如何使带有@ResponseBody
注释的控制器方法返回UTF-8,而不必每次都提供produces
吗?
Can someone explain what the registered HttpMessageConverter
actually does, and how to make @ResponseBody
-annotated controller methods return UTF-8 without having to provide produces
every time?
修改
正如评论中所讨论的那样,为了使工作正常,我不得不将Spring Boot的版本从0.5.0.M6
升级到0.5.0.BUILD-SNAPSHOT
,并且为了防止输出垃圾头,请在
As discussed in the comments, for the accepted answer to work, I had to upgrade the version of Spring Boot from 0.5.0.M6
to 0.5.0.BUILD-SNAPSHOT
and, to prevent outputting a junk header, call converter.setWriteAcceptCharset(false)
on the StringHttpMessageConverter
.
推荐答案
StringHttpMessageConverter
的默认字符集是ISO-8859-1
.这意味着当客户端不请求特定的字符集时,将返回ISO-8859-1
.
The default character set for the StringHttpMessageConverter
is ISO-8859-1
. That means when a client does not request a specific character set, then ISO-8859-1
will be returned.
如果希望UTF-8
作为默认字符集,则将其传递给构造函数:
If you want UTF-8
to be the default character set then you pass it into the constructor:
converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
由于自动添加了text/plain; charset=default character set
,因此不再需要调用setSupportedMediaTypes()
.
Calling setSupportedMediaTypes()
is then no longer necessary either as text/plain; charset=default character set
is added automatically.
这篇关于使@ResponseBody注释的Spring(Boot)MVC控制器方法返回UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!