【发布时间】:2015-02-20 08:54:30
【问题描述】:
我在码头网络服务器(也是 tomcat)上运行基于注释的 Spring Rest 服务。控制器代码是:
@RequestMapping(method = RequestMethod.POST, value = { "/ssrfeed/exec/",
"/query/exec" }, consumes = { "application/xml", "text/xml",
"application/x-www-form-urlencoded" }, produces = {
"application/xml;charset=UTF-8", "text/xml;charset=UTF-8",
"application/x-www-form-urlencoded;charset=UTF-8" })
@ResponseBody
protected String getXmlFeed(HttpServletRequest request,
@PathVariable String serviceName, @RequestBody String xmlReq) {
//code....
return appXMLResponse;
}
问题是控制器返回的响应 xml 包含一些字符,如 ä ö ü(元音变音符号)。在浏览器上呈现的响应给出了解析错误:
XML Parsing Error: not well-formed
Location: //localhost:8083/MySerice/ssrfeed/exec/
Line Number 18111, Column 17:
<FIRST_NAME>Tzee rfista</FIRST_NAME>
----------------^
(一个小三角形出现在ü的位置)
The expected is : <FIRST_NAME>Tzeeürfista</FIRST_NAME>
我尝试了以下解决方案,但问题仍然存在。
参考technowobble上给出的解决方案尝试使用过滤器
-
将字符集传递给 StringHttpMessageConverter 属性
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json" /> </bean> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes" value="text/xml;charset=UTF-8" /> </bean> </list> </property> </bean> 在tomcat -web.xml中启用
SetCharacterEncodingFilter-
将代码更改为返回
ResponseEntity而不是String并删除@ResponseBody。protected ResponseEntity<String> getXmlFeed(HttpServletRequest request, @PathVariable String serviceName, @RequestBody String xmlReq) { //line of code HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("Content-Type", "application/xml; charset=utf-8"); return new ResponseEntity<String>(appXMLResponse, responseHeaders, HttpStatus.CREATED); }
第 4 个解决方案有效但这是现有代码,我无法更改方法签名,因为它可能会影响该服务的现有客户端。任何想法/指针来解决这个问题?
【问题讨论】:
标签: spring utf-8 character-encoding response resttemplate