AJAX中文乱码问题

产生乱码的原因
用XMLHTTP对象Post表单的时候,是默认的用UTF-8字符来发送的。如果你的网页本来就是用的UTF-8编码的话,那么接收到的数据是正常的;如果你的网页编码是GB2312的话,问题就来了,POST过来的数据是UTF-8,而你整个站点是用GB2312来显示,那么所有的中文字符将全部变成乱码。
解决办法:
过滤器用UTF-8编码,就行了。
简单例子:
public class Encode
implements Filter
{
protected String encoding = "GBK";
protected FilterConfig filterConfig = null;
/**
* 是否将客户端报告的Encoding设置忽略,强制使用我们设置的Encoding?
* 默认是忽略
*/
protected boolean ignore = true;
public void destroy()
{
this.encoding = null;
this.filterConfig = null;
}
/**
* 对当前request进行encoding设置(如果不选择忽略客户端设置的话)
* @param request 当前处理的SevletRequest
* @param result 当前处理的SevletResponse
* @param chain 当前Filter链
* @exception IOException I/O错误发生
* @exception ServletException Servelt错误发生
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{
//若设置覆盖客户端设置或者客户端设置为null,则应用
//当前的encoding设置(从初始化参数中读取)
if (ignore || (request.getCharacterEncoding() == null))
{
String encoding = selectEncoding(request);
if (encoding != null)
{
request.setCharacterEncoding(encoding);
}
}
chain.doFilter(request, response);
}
/**
* 初始化
* @param filterConfig Filter设置对象
*/
public void init(FilterConfig filterConfig)
throws ServletException
{
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
{
this.ignore = true;
}
else if (value.equalsIgnoreCase("true"))
{
this.ignore = true;
}
else if (value.equalsIgnoreCase("yes"))
{
this.ignore = true;
}
else
{
this.ignore = false;
}
}
/**
* <b>功能说明:返回当前的Encoding设置</b><br>
*
* @param
* @return
* @exception
*/
protected String selectEncoding(ServletRequest request)
{
return (this.encoding);
}
}
部署描述文件:
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.pub.dragon.sys.Encode</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>ignore</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

还有一个很重要的是,如果返回XML格式的话一定要带上<?xml version="1.0" encoding="GBK"?>否则客户接受会出错...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值