Servlet开发GET和POST中文乱码处理(原创)

来源:互联网 发布:专业软件测试培训 编辑:程序博客网 时间:2024/05/17 02:06
Servlet开发GET和POST中文乱码处理(原创)
作者:余超 email:yuchao86@gmail.com


tomcat在开发WEB服务器端程序的时候,我们经常遇到中文乱码的情况
现在特殊说明如下,主要要清除几个概念:
1.JAVA class类的编码是Unicode统一编码的,支持中文和其他UTF-8的字符用作类名等等;
2.TOMCAT内部实现的编码方式,TOMCAT的默认是以ISO-8859-1作为默认的编码。
2.request,response请求和响应的编码方式。


TOMCAT的执行机制:GET和POST有区别:
首先TOMCAT内核以指定的编码conf/server.xml中(URIEncoding=“GBK”)来读取Unicode的class的byte编码文件
到TOMCAT内核运行机制,等待请求,对于GET方式使用request.setCharacterEncoding("GBK")指定的编码读入TOMCAT,
在获取字符串str时使用str = new String(str.getBytes("ISO-8859-1"),"GB2312")因为TOMCAT的编码为ISO-8859-1
所以在获取中文字符时一定要使用如上才可以获取到正确字符。
对于POST获得的数据,使用request.setCharacterEncoding("GBK")指定的编码读入TOMCAT,在获取字符时候直接使用
str = getParameter("variables")就可以了,如果有返回,直接按照response.setContentType("text/html; charset=GBK")指定的编码返回。


另外一个问题是怎么样改变POST方法的提交的数据编码方式?
 
POST请求需要指定它发送的参数和值的编码,因为大多数客户端可能没有设置一个明确的编码,默认使用的是ISO-8859-1,因此可以使用一个javax.servlet.Filter来改变编码。Tomcat已经提供了完成这个功能的过滤器的例子。请参看:
6.x 
webapps/examples/WEB-INF/classes/filters/SetCharacterEncodingFilter.java


如下是一个实例验证GET和POST提交中文参数的过程:
建一个form.html
文件如下:
<body>
<form action="./TestServlet" method="GET">
<input name="username">
<input type="submit">
</form>
</BR>
<form action="./TestServlet" method="POST">
<input name="username">
<input type="submit">
</form>
</body>


在TestServlet.java文件中修改代码最终的代码如下:


public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
   request.setCharacterEncoding("GBK");
   response.setContentType("text/html;charset=GBK");
   PrintWriter out = response.getWriter();
   out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">");
   out.println("<HTML>");
   out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
   out.println(" <BODY>");
   out.print("你输入的用户名:");
   //GET方法代码转换
   String username=request.getParameter("username");
   username =new String(username.getBytes("ISO8859-1"),"GBK");
   out.print(username);
   out.println(", using the GET method");
   out.println(" </BODY>");
   out.println("</HTML>");
   out.flush();
   out.close();
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
   request.setCharacterEncoding("GBK");
   //response.setContentType("text/html");
  response.setContentType("text/html;charset=GBK");
   PrintWriter out = response.getWriter();
   out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">");
   out.println("<HTML>");
   out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
   out.println(" <BODY>");
   out.print("你输入的用户名:");
   out.print(request.getParameter("username"));
   out.println(", using the POST method");
   out.println(" </BODY>");
   out.println("</HTML>");
   out.flush();
   out.close();
}
输入中文名,测试doGet(),doPost都无乱码。


测试通过,例子参考了互联网上的很多资源,如有异议,请联系作者,遗漏之处敬请指正。
原创粉丝点击