encodeURIComponent()与encodeURI()

来源:互联网 发布:linux如何安装vim 编辑:程序博客网 时间:2024/06/05 14:45

encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。
encodeURIComponent(URIstring)
该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。

 

encodeURI() 函数可把字符串作为 URI 进行编码。
encodeURI(URIstring)
该方法的目的是对 URI 进行完整的编码,因此对以下在 URI 中具有特殊含义的 ASCII 标点符号,encodeURI() 函数是不会进行转义的:;/?:@&=+$,#

 

encodeURIComponent() 函数 与 encodeURI() 函数的区别之处:

前者假定它的参数是 URI 的一部分(比如协议、主机名、路径或查询字符串).

 

要连续两次调用 encodeURI(String) 方法
是因为 Java 中的 request.getParameter(String) 方法会进行一次 URI 的解码过程,调用时内置的解码过程会导致乱码出现。
而 URI 编码两次后, request.getParameter(String) 函数得到的是原信息 URI 编码一次的内容。
接着用 java.net.URLDecoder.decode(String str,String codename) 方法,将已经编码的 URI 转换成原文。

 

Js代码
  1. comment=encodeURIComponent("http://cang.baidu.com/bruce42");   
  2. var pdata="method=updateComment&date="+dateStr+"&comment="+comment;    
  3. pdata=encodeURI(encodeURI(pdata));  

 

Java代码
  1. //BookingDaysCommentForm.java   
  2. public void setComment(String comment) {   
  3.     try {   
  4.         this.comment = java.net.URLDecoder.decode(comment,"utf-8");   
  5.     } catch (UnsupportedEncodingException e) {   
  6.         // TODO Auto-generated catch block  
  7.         this.comment = comment;   
  8.         LOGGER.error("Decode comment error:"+e.getMessage());   
  9.     }catch (RuntimeException re){   
  10.         this.comment = comment;   
  11.         LOGGER.error("Decode comment RuntimeException:"+re.getMessage());   
  12.     }    
  13. }     

 

 

Java代码
  1. //BookingDaysCommentOpenAction.java   
  2. String formatComment = formBean.getComment();   
  3. formatComment = java.net.URLDecoder.decode(formatComment,"utf-8");

后台编码时候 前台空格变成+ 处理方式:

java.net.URLEncoder.encode("测试","UTF-8").replace("+", "%20");
前台 decodeURI(str)



原创粉丝点击