GET提交方式参数编/解码过程
时间:2011-05-15 来源:此山之玉
GET方式访问URL时参数的编解码工作:编码/传输/解码
基本过程:
public static void main(String args[]){
String tsptString=”中文”;
//1.编码(浏览器会按网页的编码方式进行编码)
String tempString=URLEncoder.encode(tsptString,”GBK”);
//2.传输
System.out.println(tempString);
//3.解码(由Tomcat容器按照默认编码方式自动解码)
String resultString=URLDecoder.decode(tempString,”ISO-8859-1”);
//查看
System.out.println(resultString);
}
上面的方式会因为编解码方式的不统一导致乱码,可以通过下面的方式来统一编码方式:
1.客户端指定网页编码
a) 页面指定GBK方式: submit.jsp 中 <%@ page pageEncoding="GBK"%> ,Servelet中Response.setContentType(“text/html; charset=GBK”);
b) 浏览器指定GBK方式:在页面上右击->编码->选择新编码->GBK(无法依靠用户为你的页面指定编码,但要预防用户通过这种方法改变你的编码方式
2.服务端改变编码
a) 改变Tomcat的默认编码方式:打开tomcat下的conf文件夹下的service.xml查找8080,添加 URIEncoding='GBK',如下: <Connector port="8080" maxThreads="150" … URIEncoding='GBK' />,实例中此时第三步的默认编码方式就变成了GBK
b) 不使用TOMCAT的默认编码方式在服务器端处理参数,例如在Servlet中
protected void service(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException { String param=arg0.getParameter("param"); //UTF-8为指定的页面编码方式,ISO-8859-1为TOMCAT的默认解码方式(URIEncoding) param =new String(param.getBytes("ISO-8859-1"),"UTF-8"); System.out.println(param); //... }
3.利用jS两次编码
String toTspt="中文";
//进行两次一次编码,使用js时 可以这样 var params="name="+URIEncode(URIEncode(valueOfName))+"&age="+...;
String tempString=URLEncoder.encode(URLEncoder.encode(toTspt, "UTF-8"), "UTF-8");
//传送,浏览器不会再进行编码,因为没有特殊字符
System.out.println(tempString);
//解析,这里不管TOMCAT默认的什么编码方式都可以正确解码(没有特殊字符)
tempString=URLDecoder.decode(tempString,"ISO-8859-1");
//获取结果
String resultString=URLDecoder.decode(tempString, "UTF-8");
相关阅读 更多 +
排行榜 更多 +