springmvc 在web配置了编码拦截器配置

接手一个新的项目,在项目中碰见了编码问题,在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


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值