这里的方案是页面(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
- <%@ 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提交" οnclick= "doRequestUsingGET();" >
- <br>
- <input type="button" value= "使用POST提交" οnclick= "doRequestUsingPOST();" >
- </form>
- <br>
- <br>
- <h2>服务器返回信息:</h2>
- <div id="serverResponse" >
- </div>
- </body>
- </html>
<%@ 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提交" οnclick="doRequestUsingGET();">
<br>
<input type="button" value="使用POST提交" οnclick="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" );
- }
- }
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 ;
- }
- }
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>