转《Java的AJAX请求中文编码方法》

转《Java的AJAX请求中文编码方法

 

关键字: AJAX   AJAX 中文乱码 乱码 编码 中文编码    

这里的方案是页面(page)是基于GBK(gb2312) 的编码格式

AJAX的中文情况,默认情况下,tomcat和weblogic的get和post请求的编码方案都不一样,不过前提都是要设置request.setCharactorEncoding("UTF-8")如下面代码中,get方案是很烦琐的那种将得到的参数重新编码来实现的|new String(request.getParameter("para name").getBytes("encoding name"))|而post方案是比较简单而方便的,也提倡使用这种方式,因为可以基于filter来管理编码
tomcat可以通过设置在server.xml里的Connector元素下设置URIencoding="gbk"参数来让get使用post的方案(即get和post都使用request.setCharactorEncoding("UTF-8"),request.getParameter("para name") )具体设置参考http://www.iteye.com/topic/131542,不过在weblogic下无解(我个人还没发现如何实现),weblogic好像在解析get参数后自己又用什么编码格式包装过......其实AJAX get根本没有普通请求get请求作为标签的作用,我们完全可以不使用get,而只使用post

测试用的jsp和servlet在下面,丢到一个项目里,在web.xml里配置servlet后运行可以看到效果,servlet的url-pattern是这个<url-pattern>/GetAndPostExample</url-pattern>

getAndPostExample.jsp

代码
  1. <%@ page language="java" import="java.util.Date"  contentType="text/html; charset=gbk"%>  
  2. <html>  
  3.     <head>  
  4.         <title>发送带参数的信息到服务器,以及get,post的区别</title>  
  5.         <script type="text/javascript">  
  6.             var xmlHttp;               
  7.             function show()   
  8.                 {   
  9.                 document.getElementById("show").value=document.getElementById("firstName").value;   
  10.                 }   
  11.             function createXMLHttpRequest()   
  12.                 {   
  13.                 if (window.ActiveXObject)   
  14.                     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");   
  15.                 else if (window.XMLHttpRequest)   
  16.                     xmlHttp = new XMLhttpRequest();   
  17.                 }   
  18.                
  19.             function createQueryString()   
  20.                 {   
  21.                 var firstName = document.getElementById("firstName").value;   
  22.                 var secondName = document.getElementById("secondName").value;   
  23.                 var birthday = document.getElementById("birthday").value;   
  24.                    
  25.                 var queryString = "firstName="+firstName+"&secondName="+secondName   
  26.                                                 +"&birthday="+birthday;   
  27.                 return queryString;   
  28.                 }   
  29.                
  30.             function doRequestUsingGET()   
  31.                 {   
  32.                 createXMLHttpRequest();   
  33.                 show();   
  34.                 var queryString = "GetAndPostExample?";   
  35.                 queryStringqueryString = queryString + createQueryString()   
  36.                                         + "&timeStamep=" + new Date().getTime();   
  37.                 xmlHttp.onreadystatechange = handleStateChange;   
  38.                 xmlHttp.open("GET",queryString,true);   
  39.                                     xmlHttp.setRequestHeader("RequestType","ajax");   
  40.                 xmlHttp.send(null);   
  41.                 //alert(queryString);   
  42.                 }   
  43.                    
  44.             function doRequestUsingPOST()   
  45.                 {   
  46.                 createXMLHttpRequest();   
  47.                 show();        
  48.                 var url = "GetAndPostExample"  
  49.                 var queryString = createQueryString()+ "&timeStamp="+ new Date().getTime();            
  50.                 xmlHttp.open("POST",url,true);   
  51.                 xmlHttp.onreadystatechange = handleStateChange;   
  52.                 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");   
  53.                                      //设置报头,说明此请求是ajax请求   
  54.                                      xmlHttp.setRequestHeader("RequestType","ajax");   
  55.                 xmlHttp.send(queryString);   
  56.                 }   
  57.                    
  58.             function handleStateChange()   
  59.                 {   
  60.                 if (xmlHttp.readyState == 4)   
  61.                     {   
  62.                     if (xmlHttp.status == 200)   
  63.                         parseResults();   
  64.                     }   
  65.                 }   
  66.                
  67.             function parseResults()   
  68.                 {   
  69.                 var responseDiv = document.getElementById("serverResponse");   
  70.                 if (responseDiv.hasChildNodes())   
  71.                     {   
  72.                     responseDiv.removeChild(responseDiv.childNodes[0]);   
  73.                     }   
  74.                 var responseText = document.createTextNode(xmlHttp.responseText);   
  75.                 responseDiv.appendChild(responseText);   
  76.                 }   
  77.                
  78.         </script>  
  79.     </head>  
  80.     <body>  
  81.         <h1>输入你的姓,名,生日日期</h1>  
  82.         <br>  
  83.            
  84.             <table>  
  85.                 <tr>  
  86.                     <td>  
  87.                         姓:   
  88.                     </td>  
  89.                     <td>  
  90.                         <input type="text" name="firstName" id="firstName" value="羽飞">  
  91.                     </td>  
  92.                 </tr>  
  93.                     <td>  
  94.                         名:   
  95.                     </td>  
  96.                     <td>  
  97.                         <input type="text" name="secondName" id="secondName" value="翼">  
  98.                     </td>  
  99.                 <tr>  
  100.                 </tr>  
  101.                 <tr>  
  102.                     <td>  
  103.                         生日:   
  104.                     </td>  
  105.                     <td>  
  106.                         <input type="text" name="birthday" id="birthday" value="五月">  
  107.                     </td>  
  108.                     <td>  
  109.                         <input type="text" name="show" id="show">  
  110.                     </td>  
  111.                 </tr>  
  112.             </table>  
  113.         <form action="#">  
  114.             <input type="button" value="使用GET提交" onclick="doRequestUsingGET();">  
  115.             <br>  
  116.             <input type="button" value="使用POST提交" onclick="doRequestUsingPOST();">  
  117.         </form>  
  118.         <br>  
  119.         <br>           
  120.         <h2>服务器返回信息:</h2>          
  121.         <div id="serverResponse">  
  122.         </div>  
  123.     </body>  
  124. </html>  
<script>render_code();</script>

 

GetAndPostExample.java

代码
  1. package yufei;   
  2.   
  3. import java.io.*;   
  4. import java.net.*;   
  5. import javax.servlet.*;   
  6. import javax.servlet.http.*;   
  7.   
  8. public class GetAndPostExample extends HttpServlet   
  9.     {   
  10.         protected void processRequest(HttpServletRequest request,   
  11.                 HttpServletResponse response, String method1)   
  12.                 throws ServletException,IOException   
  13.                 {   
  14.                 //设置文本类型(content type)   
  15.                 response.setContentType("text/xml");   
  16.                                      //设置文本类型的编码格式   
  17.                 response.setCharacterEncoding("GBK");   
  18.                 response.setHeader("Cache-Control","no-cache");   
  19.                    
  20.                 String firstName =null;   
  21.                 String secondName = null;   
  22.                 String birthday = null;   
  23.                                     //无论是get还是post,都要使用下面这句   
  24.                                     request.setCharacterEncoding("UTF-8");   
  25.                 if (method1.equals("GET"))   
  26.                 {                   
  27.                  firstName = new String(request.getParameter("firstName").getBytes("ISO8859-1"));   
  28.                  secondName = new String(request.getParameter("secondName").getBytes("ISO8859-1"));   
  29.                  birthday = new String(request.getParameter("birthday").getBytes("ISO8859-1"));   
  30.                 }   
  31.                 else if (method1.equals("POST"))   
  32.                 {                            firstName = request.getParameter("firstName");   
  33.                  secondName = request.getParameter("secondName");   
  34.                  birthday = request.getParameter("birthday");   
  35.                 }      
  36.                 String responseText = "Hello " + firstName + " " + secondName   
  37.                                 + " 你的生日是 " + birthday + " " + "(method: " + method1 + ")";                
  38.                 PrintWriter out = response.getWriter();   
  39.                 out.println(responseText);   
  40.                    
  41.                 out.close();   
  42.                 }   
  43.         protected void doGet(HttpServletRequest request,   
  44.                 HttpServletResponse response)   
  45.                 throws ServletException,IOException   
  46.                 {   
  47.                 processRequest(request,response,"GET");   
  48.                 }   
  49.         protected void doPost(HttpServletRequest request,   
  50.                 HttpServletResponse response)   
  51.                 throws ServletException,IOException   
  52.                 {   
  53.                 processRequest(request,response,"POST");   
  54.                 }   
  55.     }   
<script>render_code();</script>

 

-
-

当我们的ajax请求只使用post(tomcat下可以实现get和post同样方案)请求时,我们可以使用过滤器来实现其编码设置,就可以把servlet中的request.setCharactorEncoding提出来,去掉servlet里的request.setCharactorEncoding("encoding name"),加入下面的过滤器
根据fins大大的指导,将过滤器重写为可以区分普通请求和ajax请求的样式了(ajax请求中设置了header)

SetCharacterEncodingFilter.java

代码
  1. package yufei;   
  2.   
  3. import java.io.IOException;   
  4. import javax.servlet.FilterChain;   
  5. import javax.servlet.FilterConfig;   
  6. import javax.servlet.ServletException;   
  7. import javax.servlet.ServletRequest;   
  8. import javax.servlet.ServletResponse;   
  9. import javax.servlet.Filter;   
  10. import javax.servlet.http.HttpServletRequest;   
  11.   
  12. public class CharactorEncodingFilter implements Filter   
  13.     {   
  14.     public CharactorEncodingFilter()   
  15.         {   
  16.         super();   
  17.         }   
  18.     private FilterConfig filterConfig;   
  19.     private String ajaxEncoding = "UTF-8";   
  20.     private String commonEncoding;   
  21.     protected boolean ignore = true;   
  22.     public void init(FilterConfig filterConfig) throws ServletException   
  23.         {   
  24.         this.filterConfig = filterConfig;   
  25.         commonEncoding = filterConfig.getInitParameter("CommonRequestEncoding");   
  26.         String value = filterConfig.getInitParameter("ignore");   
  27.         if (value == null)   
  28.             this.ignore = true;   
  29.         else if (value.equalsIgnoreCase("true"))   
  30.             this.ignore = true;   
  31.         else if (value.equalsIgnoreCase("yes"))   
  32.             this.ignore = true;   
  33.         else  
  34.             this.ignore = false;   
  35.         }   
  36.   
  37.     public void doFilter(ServletRequest req, ServletResponse res,   
  38.         FilterChain filterChain)   
  39.   
  40.         {   
  41.         try  
  42.             {   
  43.             HttpServletRequest request = (HttpServletRequest) req;   
  44.             if (ignore || (request.getCharacterEncoding() == null))   
  45.                 {   
  46.                 if (request.getHeader("RequestType") != null  
  47.                     && request.getHeader("RequestType")   
  48.                         .equalsIgnoreCase("ajax"))   
  49.                     {   
  50.                     request.setCharacterEncoding(ajaxEncoding);   
  51.                     }   
  52.                 else if (commonEncoding != null)   
  53.                     {   
  54.                     request.setCharacterEncoding(commonEncoding);   
  55.                     }   
  56.                 else  
  57.                     {   
  58.                     request.setCharacterEncoding("UTF-8");   
  59.                     }   
  60.                 }   
  61.             filterChain.doFilter(req, res);   
  62.             }   
  63.         catch (IOException e)   
  64.             {   
  65.             e.printStackTrace();   
  66.             }   
  67.         catch (ServletException e)   
  68.             {   
  69.             e.printStackTrace();   
  70.             }   
  71.         }   
  72.     public void destroy()   
  73.         {   
  74.         this.commonEncoding = null;   
  75.         this.filterConfig = null;   
  76.         }   
  77.     }   
<script>render_code();</script>

 

web.xml加入如下过滤器配置

代码
  1. <filter>  
  2.     <filter-name>CharactorEncoding</filter-name>  
  3.     <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  
  4.                  <!-- 设置编码格式到initparameter里去 -->  
  5.     <init-param>  
  6.         <param-name>CommonRequestEncoding</param-name>  
  7.         

你可能感兴趣的:(java,tomcat,Ajax,servlet,weblogic)