我在我的Annotation驱动的Spring MVC Java Web应用程序中运行在jetty Web服务器上(目前在maven jetty插件中)。
我正在尝试使用一个控制器方法执行一些AJAX支持,只返回String帮助文本。资源采用UTF-8编码,字符串也是如此,但我的服务器响应是
content-encoding: text/plain;charset=ISO-8859-1
即使我的浏览器发送
Accept-Charset windows-1250,utf-8;q=0.7,*;q=0.7
我正在以某种方式使用spring的默认配置
我已经找到了一个提示,可以将这个bean添加到配置中,但我认为它没有被使用,因为它表示它不支持编码,而是使用默认编码。
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
</bean>
我的控制器代码是(请注意,此响应类型的更改对我不起作用):
@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;
}
答案 0 :(得分:151)
我找到了Spring 3.1的解决方案。使用@ResponseBody注释。 以下是使用Json输出的控制器示例:
@RequestMapping(value = "/getDealers", method = RequestMethod.GET,
produces = "application/json; charset=utf-8")
@ResponseBody
public String sendMobileData() {
}
答案 1 :(得分:58)
简单声明StringHttpMessageConverter
bean是不够的,你需要将它注入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>
但是,使用此方法您必须重新定义所有HttpMessageConverter
,并且它不适用于<mvc:annotation-driven />
。
所以,也许最方便但最难看的方法是用AnnotationMethodHandlerAdapter
拦截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 " />
答案 2 :(得分:48)
请注意,在Spring MVC 3.1中,您可以使用MVC命名空间来配置消息转换器:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
或基于代码的配置:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
private static final Charset UTF8 = Charset.forName("UTF-8");
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
converters.add(stringConverter);
// Add other converters ...
}
}
答案 3 :(得分:44)
以防您也可以通过以下方式设置编码:
@RequestMapping(value = "ajax/gethelp")
public ResponseEntity<String> handleGetHelp(Locale loc, String code, HttpServletResponse response) {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/html; charset=utf-8");
log.debug("Getting help for code: " + code);
String help = messageSource.getMessage(code, null, loc);
log.debug("Help is: " + help);
return new ResponseEntity<String>("returning: " + help, responseHeaders, HttpStatus.CREATED);
}
我认为使用StringHttpMessageConverter比这更好。
答案 4 :(得分:19)
你可以将yield =“text / plain; charset = UTF-8”添加到RequestMapping
@RequestMapping(value = "/rest/create/document", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String create(Document document, HttpServletRespone respone) throws UnsupportedEncodingException {
Document newDocument = DocumentService.create(Document);
return jsonSerializer.serialize(newDocument);
}
答案 5 :(得分:10)
我最近在讨论这个问题,并在Spring 3.1中找到了一个更好的答案:
@RequestMapping(value = "ajax/gethelp", produces = "text/plain")
所以,就像JAX-RS一样简单就像所有的评论所表明的那样./ / p>
答案 6 :(得分:4)
我在ContentNegotiatingViewResolver bean的MarshallingView中设置了content-type。它工作轻松,干净,流畅:
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller" />
</constructor-arg>
<property name="contentType" value="application/xml;charset=UTF-8" />
</bean>
</list>
</property>
答案 7 :(得分:4)
您可以使用产品来指示您从控制器发送的响应类型。这个“生成”关键字在ajax请求中最有用,在我的项目中非常有用
@RequestMapping(value = "/aURLMapping.htm", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
public @ResponseBody String getMobileData() {
}
答案 8 :(得分:3)
我正在使用在web.xml中配置的CharacterEncodingFilter。也许这有帮助。
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
答案 9 :(得分:3)
感谢digz6666,您的解决方案对我有用,稍微改动,因为我正在使用json:
responseHeaders.add("Content-Type", "application/json; charset=utf-8");
axtavt(你推荐的那个)给出的答案对我不起作用。即使我添加了正确的媒体类型:
if (conv instanceof StringHttpMessageConverter) { ((StringHttpMessageConverter) conv).setSupportedMediaTypes( Arrays.asList( new MediaType("text", "html", Charset.forName("UTF-8")), new MediaType("application", "json", Charset.forName("UTF-8")) )); }
答案 10 :(得分:2)
如果以上都没有为你工作,试图在“POST”上发出ajax请求而不是“GET”,那对我很有帮助......以上都没有。我也有characterEncodingFilter。
答案 11 :(得分:2)
package com.your.package.spring.fix;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* @author Szilard_Jakab (JaKi)
* Workaround for Spring 3 @ResponseBody issue - get incorrectly
encoded parameters from the URL (in example @ JSON response)
* Tested @ Spring 3.0.4
*/
public class RepairWrongUrlParamEncoding {
private static String restoredParamToOriginal;
/**
* @param wrongUrlParam
* @return Repaired url param (UTF-8 encoded)
* @throws UnsupportedEncodingException
*/
public static String repair(String wrongUrlParam) throws
UnsupportedEncodingException {
/* First step: encode the incorrectly converted UTF-8 strings back to
the original URL format
*/
restoredParamToOriginal = URLEncoder.encode(wrongUrlParam, "ISO-8859-1");
/* Second step: decode to UTF-8 again from the original one
*/
return URLDecoder.decode(restoredParamToOriginal, "UTF-8");
}
}
在我为这个问题尝试了很多解决方法之后......我想到了这一点并且工作正常。
答案 12 :(得分:2)
在Spring 3.1.1中解决此问题的简单方法是:在servlet-context.xml
中添加以下配置代码
<annotation-driven>
<message-converters register-defaults="true">
<beans:bean class="org.springframework.http.converter.StringHttpMessageConverter">
<beans:property name="supportedMediaTypes">
<beans:value>text/plain;charset=UTF-8</beans:value>
</beans:property>
</beans:bean>
</message-converters>
</annotation-driven>
不需要覆盖或实现任何内容。
答案 13 :(得分:1)
根据link“如果未指定字符编码,则Servlet规范要求使用ISO-8859-1的编码”。如果您使用的是Spring 3.1或更高版本,请使用以下配置:将charset = UTF-8设置为响应体
@RequestMapping(value =“your mapping url”,produce =“text / plain; charset = UTF-8”)
答案 14 :(得分:1)
如果您决定通过以下配置解决此问题:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
您应确认所有* .xml文件中只应有一个mvc:annotation-driven标记。 否则,配置可能无效。
答案 15 :(得分:0)
public final class ConfigurableStringHttpMessageConverter extends AbstractHttpMessageConverter<String> {
private Charset defaultCharset;
public Charset getDefaultCharset() {
return defaultCharset;
}
private final List<Charset> availableCharsets;
private boolean writeAcceptCharset = true;
public ConfigurableStringHttpMessageConverter() {
super(new MediaType("text", "plain", StringHttpMessageConverter.DEFAULT_CHARSET), MediaType.ALL);
defaultCharset = StringHttpMessageConverter.DEFAULT_CHARSET;
this.availableCharsets = new ArrayList<Charset>(Charset.availableCharsets().values());
}
public ConfigurableStringHttpMessageConverter(String charsetName) {
super(new MediaType("text", "plain", Charset.forName(charsetName)), MediaType.ALL);
defaultCharset = Charset.forName(charsetName);
this.availableCharsets = new ArrayList<Charset>(Charset.availableCharsets().values());
}
/**
* Indicates whether the {@code Accept-Charset} should be written to any outgoing request.
* <p>Default is {@code true}.
*/
public void setWriteAcceptCharset(boolean writeAcceptCharset) {
this.writeAcceptCharset = writeAcceptCharset;
}
@Override
public boolean supports(Class<?> clazz) {
return String.class.equals(clazz);
}
@Override
protected String readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException {
Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset));
}
@Override
protected Long getContentLength(String s, MediaType contentType) {
Charset charset = getContentTypeCharset(contentType);
try {
return (long) s.getBytes(charset.name()).length;
}
catch (UnsupportedEncodingException ex) {
// should not occur
throw new InternalError(ex.getMessage());
}
}
@Override
protected void writeInternal(String s, HttpOutputMessage outputMessage) throws IOException {
if (writeAcceptCharset) {
outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
}
Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType());
FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(), charset));
}
/**
* Return the list of supported {@link Charset}.
*
* <p>By default, returns {@link Charset#availableCharsets()}. Can be overridden in subclasses.
*
* @return the list of accepted charsets
*/
protected List<Charset> getAcceptedCharsets() {
return this.availableCharsets;
}
private Charset getContentTypeCharset(MediaType contentType) {
if (contentType != null && contentType.getCharSet() != null) {
return contentType.getCharSet();
}
else {
return defaultCharset;
}
}
}
示例配置:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list>
<bean class="ru.dz.mvk.util.ConfigurableStringHttpMessageConverter">
<constructor-arg index="0" value="UTF-8"/>
</bean>
</util:list>
</property>
</bean>