接手一个新的项目,在项目中碰见了编码问题,在web.xml里面配置了拦截器,来统一进行编码设置,下面是具体代码:
</pre><pre name="code" class="html"> <filter>
<filter-name>encodingFilter</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>
<span style="color:#3333ff;"><init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param></span>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
问题总结:
代码的蓝色部分要特别注意,因为如果不写的话,会出现一种问题:
虽然springmvc 在web配置了编码拦截器,并且工程都是UTF-8格式的,但是responseText中文还是乱码,使用PrintWriter的时候也是乱码。
解决的思路有两个:
1.第一种就是我上面说的,使用这个配置。知其然更要知其所以然,具体解释:①http://blog.csdn.net/name_xiaoai/article/details/26059859 ②http://my.oschina.net/liting/blog/509865
2.第二种就是绕开这个问题,在response里获取printwriter,要注意的是要在获取printwriter之前设置response的编码。
@RequestMapping(value="/showFlow")
public void showFlow(HttpServletRequest request,HttpServletResponse response){
try {
JSONObject result = eCharsService.showFlows(request);
response.setContentType("text/html; charset=utf-8");
PrintWriter print = response.getWriter();
print.print(result.toString());
} catch (Exception e) {
// TODO: handle exception
log.error("异常",e);
}
}
亲测两种方法都可以,欢迎道友补充。
web.xml
2.controller