url请求中的中文字符编解码处理,encodeURI()、encodeURIComponent()区别

有些场景我们会使用get请求带中文参数的情况,如EMP框架的导出功能,必须对中文字符进行编解码处理

http://localhost:8080/cmis-plcs/exportCallCollCheckList.do?cust_name=%25E7%258E%258B%25E5%2581%25A5&equals.id_no=

前台js使用 encodeURIComponent() 编码 2次 (必须编码2次)

//导出excel
    function doExportExcel(){
        var jData = $('#queryForm').toJsonData();
        jData = parseParam(jData);
        var url = '<emp:url action="exportCallCollCheckList.do" reqParams="'+jData+'"/>';
        window.open(url);
    }

    function parseParam(param, key) {
        var paramStr = "";
        if (param instanceof String || param instanceof Number || param instanceof Boolean) {
        // 字符编码2次 paramStr
+= "&" + key + "=" + encodeURIComponent(encodeURIComponent(param)); } else { $.each(param, function(i) { var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i); paramStr += '&' + parseParam(this, k); }); } return paramStr.substr(1); };

后台中文字符解码

//中文字符解码
HttpServletRequest request = (HttpServletRequest) context.getDataValue(EMPConstance.SERVLET_REQUEST);
if (paramMap.containsKey("cust_name")) {
     String cust_name = java.net.URLDecoder.decode(request.getParameter("cust_name"), "UTF-8");
     paramMap.put("cust_name", cust_name);
}

这样就可以获取正确的中文字符了

encodeURI()、encodeURIComponent() 区别:

encodeURI()主要用于整个 URI(例如,http://www.wrox.com/illegal value.htm),而 encodeURIComponent()主要用于对URI 中的某一段(例如前面 URI 中的 illegal value.htm)进行编码。它们的主要区别在于,encodeURI()不会对本身属于 URI 的特殊字符进行编码,例如冒号、正斜杠、问号和井字号;而 encodeURIComponent()则会对它发现的任何非标准字符进行编码。
var uri = "http://www.wrox.com/illegal value.htm#start";
//"http://www.wrox.com/illegal%20value.htm#start"
alert(encodeURI(uri));
//"http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start"
alert(encodeURIComponent(uri));

  使用 encodeURI()编码后的结果是除了空格之外的其他字符都原封不动,只有空格被替换成了%20。而 encodeURIComponent()方法则会使用对应的编码替换所有非字母数字字符。这也正是可以对整个 URI 使用 encodeURI(),而只能对附加在现有 URI 后面的字符串使用 encodeURIComponent()的原因所在。

与 encodeURI()和 encodeURIComponent()方法对应的两个方法分别是 decodeURI()和 decodeURIComponent()。

其中,decodeURI()只能对使用 encodeURI()替换的字符进行解码。例如,它可将%20 替换成一个空格,但不会对%23 作任何处理,因为%23 表示井字号(#),而井字号不是使用encodeURI()替换的。同样地,decodeURIComponent()能够解码使用encodeURIComponent()编码。的所有字符,即它可以解码任何特殊字符的编码。

var uri = "http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start";
//http%3A%2F%2Fwww.wrox.com%2Fillegal value.htm%23start
alert(decodeURI(uri));
//http://www.wrox.com/illegal value.htm#start
alert(decodeURIComponent(uri)); 
这里,变量 uri 包含着一个由 encodeURIComponent()编码的字符串。在第一次调用 decodeURI()
输出的结果中,只有%20 被替换成了空格。而在第二次调用 decodeURIComponent()输出的结果中,所有特殊字符的编码都被替换成了原来的字符,得到了一个未经转义的字符串(但这个字符串并不是一个有效的 URI)


encodeURI()、encodeURIComponent()

原文地址:https://www.cnblogs.com/pluto-yang/p/12502060.html