日期:2014-05-17  浏览次数:20825 次

【求指教】jQuery发送Ajax请求Servlet端乱码问题
我用jquery发送ajax请求到servlet端,用IE 浏览器,servlet接受到的中文参数为乱码,火狐和谷歌浏览器中文显示正常
页面编码均为UTF-8;
<%@page contentType="text/html" pageEncoding="UTF-8"%>

$(function(){
  var word = document.getElementById("searchinput").value;
  //alert(word);
  $.ajax({
  async:false,
  dataType:'json',
  type:"get",
  url:"search.do?op=" + op + "&keyword=" + word,
  success:function(json){
  ……  
  });
  });

servlet端代码为
  response.setContentType("text/html;charset=UTF-8");
  String keyword = request.getParameter("keyword");
  //keyword = new String(keyword.getBytes("ISO-8859-1"), "GBK");
  System.out.println("keyword-->" + keyword);
  试过keyword = new String(keyword.getBytes("ISO-8859-1"), "GBK"); 输出的keyword=?????,还是乱码 

也添加了Filter,代码如下
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CharsetFilter implements Filter {
private String charset = "UTF-8";

  @Override
public void destroy() {

}

  @Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
if (request.getMethod().equalsIgnoreCase("post"))
request.setCharacterEncoding(charset);
else {
//System.out.println(charset);
EncodingRequest erq = new EncodingRequest(request, charset);
req = erq;
}
chain.doFilter(req, resp);
}

public void init(FilterConfig config) throws ServletException {
String charset = config.getInitParameter("CHARSET");
if (charset != null && charset.equals(""))
this.charset = charset;
}
}

------解决方案--------------------
Servlet端代码再加一句:request.setCharacterEncoding("UTF-8");
------解决方案--------------------
ajax 应该编码了才提交
encode()
------解决方案--------------------
在tomcat中修改sever.xml文件 在http配置项中
添加如下配置 URIEncoding = "UTF-8"