日期:2014-05-16  浏览次数:20354 次

Servlet、Jsp乱码问题(二)

??? 在上一章节提到了Get()请求方式在Servlet处理中出现乱码的问题,使用的解决方案是字符串的强制编码方式。Post()请求可以通过HttpServletRequest对象的request.setCharacterEncoding("字符集,GBK或者UTF-8");来解决。
????那么,为什么在Servlet中对两种请求方式的乱码处理需要区别对待呢?这就是本次要跟大家来讲解的内容。是不是除了强制转码的方式,Get()就不能使用和Post()一样的处理方式来解决了么?答案当然是否定的。

????我们先来看一下原来两种请求的解决方案。

public void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 

String uname = request.getParameter("name"); 
System.out.println(uname);//乱码 

if(uname!=null){ 
//将uname的值通过原来的编码方式(ISO-8859-1)转换成可显示中文的编码(GB2312) 
uname=new String(uname.getBytes("ISO-8859-1"),"GB2312"); 
}else{ 
uname="游客"; 
} 
System.out.println(uname);//输出中文“琳达” 
// 省略 
}

?

public void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 

//请求的页面设置了GBK方式进行编码,那么通过request来设置获取的对应编码
//如果请求式为Get()则此代码无效
request.setCharacterEncoding("GBK"); 
String uname = request.getParameter("name"); 
System.out.println(uname);//正常的文字 
// 省略 
}

?

??? 为什么在Servlet中对两种请求方式的乱码处理需要区别对待呢?
??? Post()请求下URL encode的方式取决于Jsp和Html页面的字符集设置,这是开发人员可以指定的,但是Get()请求下的URL encode对上面的做法却不予理会。
????看servlet的官方API说明有对request.setCharacterEncoding("字符集,GBK或者UTF-8");方法的解释:Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or reading input using getReader().那么Get()请求在Servlet中使用request.getParameter("name");即使对setCharacterEncoding("字符集")进行了设置,还是会出现乱码。可以看出对于Get()方法他是无能为力的。
????
????网上有这样的处理方法,介绍给大家。

<Connector port="8080" protocol="HTTP/1.1" maxThreads="150" connectionTimeout="20000" redirectPort="8443" URIEncoding="GBK"/>

?

??? 这样Tomcat的解码方式就从默认的“ISO-8859-1”变成现在的“GBK”,让Tomcat使用指定的方式进行URL decode(解码)。
??? Get()、Post()请求下都适用的处理方法:

?

public void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 

//请求的页面设置了GBK方式进行编码,那么通过request来设置获取的对应编码 
//如果请求方式为Get()这样也有效了!
request.setCharacterEncoding("GBK"); 
String uname = request.getParameter("name"); 
System.out.println(uname);//正常的文字 
// 省略 
}

??? 本章的讲解,主要对Get()方式乱码的解决方案提出了补充的方法——对Tomcat的URL encode进行指定。原来使用强制转码来还原数据就是因为Tomcat的默认解码方式ISO-8859-1。问题出在哪里,我们就在哪里进行解决。

??? 期待大家的关注,也希望得到宝贵的建议。