JSP解决提交乱码问题

自从Tomcat5.x开始,GET和POST方法提交的信息,Tomcat采用了不同的方式来处理编码,对于POST请求,Tomcat会仍然使用request.setCharacterEncoding方法所设置的编码来处理,如果未设置,则使用默认的iso-8859-1编码。而GET请求则不同,Tomcat对于GET请求并不会考虑使用request.setCharacterEncoding方法设置的编码,而会永远使用iso-8859-1编码。

解决办法如下:

1.配置tomcat的配置文件server.xml里这句:
             <Connector URIEncoding="GB2312" 
                 port="8080"   maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true" />


                 加上这句:URIEncoding="GB2312"
2.使用String name=new String(request.getParameter("name").getBytes("ISO-8859-1"),"GB2312");转化编码

推荐使用第二种方式。

<%@ page contentType="text/html;charset=utf-8"%>
<HTML>
<HEAD>
<TITLE>Request's and Post's Example</TITLE>
</HEAD>
<BODY>
<FORM name="msg" action="Example2_1.jsp" method="post">
<INPUT type="text" name="girl"/>
<INPUT type="submit" name="submit" value="Enter"/>
</FORM>
<%
String msg = request.getParameter("girl");
String s = "世界";
byte b[] = s.getBytes("GB2312");
s = new String(b);
out.print("<BR/>"+s);
out.print("<BR/>"+msg);
byte bb[] = msg.getBytes("ISO-8859-1");
msg = new String(bb, "utf-8");
out.print("<BR/>"+msg);
%>

</BODY>
</HTML>

原文地址:https://www.cnblogs.com/something/p/2858322.html