浏览 12751 次
锁定老帖子 主题:Java的AJAX请求中文编码方法
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2007-10-15
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 <%@ page language="java" import="java.util.Date" contentType="text/html; charset=gbk"%> <html> <head> <title>发送带参数的信息到服务器,以及get,post的区别</title> <script type="text/javascript"> var xmlHttp; function show() { document.getElementById("show").value=document.getElementById("firstName").value; } function createXMLHttpRequest() { if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); else if (window.XMLHttpRequest) xmlHttp = new XMLhttpRequest(); } function createQueryString() { var firstName = document.getElementById("firstName").value; var secondName = document.getElementById("secondName").value; var birthday = document.getElementById("birthday").value; var queryString = "firstName="+firstName+"&secondName="+secondName +"&birthday="+birthday; return queryString; } function doRequestUsingGET() { createXMLHttpRequest(); show(); var queryString = "GetAndPostExample?"; queryString = queryString + createQueryString() + "&timeStamep=" + new Date().getTime(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("GET",queryString,true); xmlHttp.setRequestHeader("RequestType","ajax"); xmlHttp.send(null); //alert(queryString); } function doRequestUsingPOST() { createXMLHttpRequest(); show(); var url = "GetAndPostExample" var queryString = createQueryString()+ "&timeStamp="+ new Date().getTime(); xmlHttp.open("POST",url,true); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;"); //设置报头,说明此请求是ajax请求 xmlHttp.setRequestHeader("RequestType","ajax"); xmlHttp.send(queryString); } function handleStateChange() { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) parseResults(); } } function parseResults() { var responseDiv = document.getElementById("serverResponse"); if (responseDiv.hasChildNodes()) { responseDiv.removeChild(responseDiv.childNodes[0]); } var responseText = document.createTextNode(xmlHttp.responseText); responseDiv.appendChild(responseText); } </script> </head> <body> <h1>输入你的姓,名,生日日期</h1> <br> <table> <tr> <td> 姓: </td> <td> <input type="text" name="firstName" id="firstName" value="羽飞"> </td> </tr> <td> 名: </td> <td> <input type="text" name="secondName" id="secondName" value="翼"> </td> <tr> </tr> <tr> <td> 生日: </td> <td> <input type="text" name="birthday" id="birthday" value="五月"> </td> <td> <input type="text" name="show" id="show"> </td> </tr> </table> <form action="#"> <input type="button" value="使用GET提交" onclick="doRequestUsingGET();"> <br> <input type="button" value="使用POST提交" onclick="doRequestUsingPOST();"> </form> <br> <br> <h2>服务器返回信息:</h2> <div id="serverResponse"> </div> </body> </html> GetAndPostExample.java package yufei; import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; public class GetAndPostExample extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response, String method1) throws ServletException,IOException { //设置文本类型(content type) response.setContentType("text/xml"); //设置文本类型的编码格式 response.setCharacterEncoding("GBK"); response.setHeader("Cache-Control","no-cache"); String firstName =null; String secondName = null; String birthday = null; //无论是get还是post,都要使用下面这句 request.setCharacterEncoding("UTF-8"); if (method1.equals("GET")) { firstName = new String(request.getParameter("firstName").getBytes("ISO8859-1")); secondName = new String(request.getParameter("secondName").getBytes("ISO8859-1")); birthday = new String(request.getParameter("birthday").getBytes("ISO8859-1")); } else if (method1.equals("POST")) { firstName = request.getParameter("firstName"); secondName = request.getParameter("secondName"); birthday = request.getParameter("birthday"); } String responseText = "Hello " + firstName + " " + secondName + " 你的生日是 " + birthday + " " + "(method: " + method1 + ")"; PrintWriter out = response.getWriter(); out.println(responseText); out.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { processRequest(request,response,"GET"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { processRequest(request,response,"POST"); } } - - 当我们的ajax请求只使用post(tomcat下可以实现get和post同样方案)请求时,我们可以使用过滤器来实现其编码设置,就可以把servlet中的request.setCharactorEncoding提出来,去掉servlet里的request.setCharactorEncoding("encoding name"),加入下面的过滤器 根据fins大大的指导,将过滤器重写为可以区分普通请求和ajax请求的样式了(ajax请求中设置了header) SetCharacterEncodingFilter.java package yufei; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.Filter; import javax.servlet.http.HttpServletRequest; public class CharactorEncodingFilter implements Filter { public CharactorEncodingFilter() { super(); } private FilterConfig filterConfig; private String ajaxEncoding = "UTF-8"; private String commonEncoding; protected boolean ignore = true; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; commonEncoding = filterConfig.getInitParameter("CommonRequestEncoding"); 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; } public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) { try { HttpServletRequest request = (HttpServletRequest) req; if (ignore || (request.getCharacterEncoding() == null)) { if (request.getHeader("RequestType") != null && request.getHeader("RequestType") .equalsIgnoreCase("ajax")) { request.setCharacterEncoding(ajaxEncoding); } else if (commonEncoding != null) { request.setCharacterEncoding(commonEncoding); } else { request.setCharacterEncoding("UTF-8"); } } filterChain.doFilter(req, res); } catch (IOException e) { e.printStackTrace(); } catch (ServletException e) { e.printStackTrace(); } } public void destroy() { this.commonEncoding = null; this.filterConfig = null; } } web.xml加入如下过滤器配置 <filter> <filter-name>CharactorEncoding</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> <!-- 设置编码格式到initparameter里去 --> <init-param> <param-name>CommonRequestEncoding</param-name> <param-value>GBK</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharactorEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2007-10-15
不用2312,全部页面都用utf8即可
|
|
返回顶楼 | |
发表时间:2007-10-15
UTF-8我出现过乱码....页面里
UTF-8在某些情况还是会有乱码...虽然几率不高... 我用GB18030也出现过乱码(新国标码,可能支持不够吧),页面里 |
|
返回顶楼 | |
发表时间:2007-10-15
回楼主 你这不能叫方案 只能叫"解决ajax乱码的基本方法"
所谓方案应该更系统 更周全. 我问个问题, 如果不是用UTF-8的系统怎么办? 正确的"方案"应该是 后台编码过滤器可以自动分析请求是 ajax还是普通请求. 普通请求则使用 web.xml里配置的编码 ajax请求则使用utf-8 判断的方式很多 常见的也是最好的方案是 在ajax请求里设置 header信息 告诉服务器这是一个ajax请求, 服务器在编码前 从header里取得信息 判断后编码 |
|
返回顶楼 | |
发表时间:2007-10-15
谢谢楼上大大的提醒,标题已经改了,楼上设置header的方法我拿去了,本来我是要连同和普通请求共存一起写的,不过发觉有不少问题要探讨,所以临时决定分开发的,不过看来没必要了
最早我是决定使用多传一个参数来区分ajax和普通请求,结果发现request.getParameter()以后再设置request.setCharactorEncoding()就不会正确(tomcat不正确,weblogic正确..)看了下j2ee-api,发现setCharactorEncoding方法的说明有以下一段This method must be called prior to reading request parameters or reading input using getReader(),看来读取header不会有影响? 后来使用了双过滤器解决了问题,不过和设置header比起来麻烦了不少,马上去试验 ...... ...... 测试OK,看来使用request.getHeader()不会影响request.setCharactorEncoding() 编辑了原文,让其可以根据header参数来区分ajax请求和普通请求了 |
|
返回顶楼 | |
发表时间:2008-08-26
这个只能是ajax适用么?如果不是AJAX怎么办呢
|
|
返回顶楼 | |