我在使用@ResponseBody注释时遇到字符编码问题。如果我使用response.getWriter().write()方法,我没有问题,我看不到像 ş、ö、ı 等土耳其语字符。(我只看到问号而不是它们)
我正在使用Spring 的 CharacterEncodingFilter和UTF-8 encoding。
我该如何解决这个问题?我是否必须将所有@ResponseBody注释使用的方法更改为response.getWriter().write()?
样品方法:
@RequestMapping(value = "/isScdValid.ajax")
public @ResponseBody String isScdValid(HttpServletRequest request, HttpServletResponse response) throws IOException {
boolean isValid = true; // for sample
// continues...
JSONObject jsonObj = new JSONObject();
jsonObj.put("isValid", isValid);
if(isValid) {
jsonObj.put("username", scd.getUsername());
jsonObj.put("sessionUserId", scd.getUserId());
}
return jsonObj.toString(); // not encoding with UTF-8
// response.getWriter().write(jsonObj.toString()); // works right
}
这是我的字符编码过滤器:
<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-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
还向 Tomcat 添加了 URIEncoding 属性:
<Connector port="9090" protocol="HTTP/1.1" connectionTimeout="20000"
redirectPort="9443"
URIEncoding="UTF-8" compression="on"
compressableMimeType="text/html,text/xml,text/javascript,text/json,text/css,text/plain,application/javascript,application/json,application/pdf"
/>