根据提交方式来防止AJAX乱码问题(比较好的解决方案)

ajax默认中文提交以utf-8格式,所以只需要在你的web服务加个过滤器,设置下编码格式即可;
1.注意为防止编码设置无效,请在编码设置完后,显示调用下request.getParameter("");(tomcat5.0测试通过)
据说其他服务器,可能显示调用了,也有可能被服务器重置;
2.有时已经有filter需要设置gbk编码,为了不影响原先的filter功能,我是直接在ajax提交时候,带个服务端要设置的编码格式 例如 Ajax.request("/myaction.do?charset=utf-8")
服务端filter,要用request.getQueryString() 截取charset值 ,注意千万不要用request.getParameter("charset");
3.注意,在没设置编码格式前,不要加 watch监控 比如有个表达式 request.getParameter("*");
首先分析通过正常GET,Post提交页面和AJAX提交页面有什么不同看截图
Get ,Post正常方式提交数据

AJAX方式提交数据

主意AJAX多了个x-requested-with信息所以可以采用获取HTTP Header方法来判断是采用那种提交方式提交数据的所以
主要代码如下
public void doFilter(ServletRequest request, ServletResponse response, 
FilterChain chain) throws IOException, ServletException {

// Conditionally select and set the character encoding to be used
HttpServletRequest httpRequest = (HttpServletRequest) request;

HttpServletResponse httpResponse = (HttpServletResponse) response;

String requestedWith = httpRequest.getHeader("x-requested-with");
String type = request.getContentType();
if (requestedWith != null && "XMLHttpRequest".equals(requestedWith)
&& null != type
&& "application/x-www-form-urlencoded".equals(type)) {
httpRequest.setCharacterEncoding("UTF-8");
httpResponse.setCharacterEncoding("UTF-8");
httpRequest.getParameterMap();
} else {

request.setCharacterEncoding("gbk");
response.setContentType("text/html;charset=" + "gbk");

}
chain.doFilter(request, response);

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值