URLEncoder.encode与URLDecoder.decode的使用

发布时间:2012-11-21 14:59:40

在传递参数的时候,如果有中文,那么可以先转码再转,之后再解码。

使用java.net.URLEncoder.encode()可以对要传递的中文进行编码
a.在传参数之前先把参数进行转码:java.net.URLEncoder.encode(param);
取值时用语句java.net.URLDecoder.decode(param);再转回中文
b.在你的Tomcat目录-->conf目录-->server.xml里找出这段:
<Connector
port="8080" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
debug="0" connectionTimeout="20000"
disableUploadTimeout="true"
<!--在里边加上这个参数-->
URIEncoding="gb2312"
/>

例如:
<%@ page contentType="text/html;charset=gb2312" %>
<a href="ds.jsp?url=<%=java.net.URLEncoder.encode("编码的是这里","GB2312")%>">点击这里</a>

使用java.net.URLDecoder.decode()在后面对传递的参数进行解码,一定要搭配使用哦
<%
if(request.getParameter("url")!=null)
{
str=request.getParameter("url");
str=java.net.URLDecoder.decode(str,"GB2312");
str=new String(str.getBytes("ISO-8859-1"));
out.print(str);
}
%>
若,字符编码为utf-8也可以实现.或者在此段代码中,不写出字符编码也可以(只写一个参数)。


ajax写法:
$.ajax({
           url:'<%=request.getContextPath()%>/cargroup-ajax/searchCargroupName.action',
           async:false,
           data:{
            cargroupName:encodeURI(cargroupName) //中文
            },
           type:'post',
           dataType:'json',
           success:function(data){
            if(data=="true"){
             if(flag!="form"){
              alert("该名称可用!");
             }
             checkRepeat = true;
            }else{
             if(flag!="form"){
              alert("该名称不可用!");
             }
            }
           }
    });
后台java:
cargroupName = URLDecoder.decode(request.getParameter("cargroupName"), "utf-8");