JS/Java 传递 中文参数
一、JS传Java
//js端需编码3次
filePath = encodeURIComponent(filePath);
filePath = encodeURIComponent(filePath);
filePath = encodeURIComponent(filePath);
//java端解码2次
(Java端request.getParameter("name")之前会自动调用一次默认的ISO-8859-1解码)
queryString = URLDecoder.decode(queryString, "UTF-8");
queryString = URLDecoder.decode(queryString, "UTF-8");
一.零、JS传Java
JS端
shopName = encodeURIComponent(shopName);
Java端
shopName = URLDecoder.decode(shopName, "UTF-8");
二、Java传JS
Java端
returnVal = URLEncoder.encode(returnVal, "UTF-8");
//将加号(+)统一改为%20,解决JS端“空格变成加号(+)的问题”
returnVal = returnVal .replace("+", "%20");
JS端
returnVal = decodeURIComponent(returnVal);
注意:前端encodeURIComponent默认不会对感叹号(!)进行编码,【感叹号在URL编码中有特殊含义】,而后端Java的URLDecoder是完整编码
解决方案:
// like12 find bug,20240605,解决前端encodeURIComponent默认不会对感叹号(!)进行编码的问题【感叹号在URL编码中有特殊含义】
sysUser.passwordNew = sysUser.passwordNew.replace(/\!/g, '%21') // g表示全局替换
完整代码:
/**
* 修改密码
*/
modifyPassword(sysUser) {
// like12 find bug,20240605,解决前端encodeURIComponent默认不会对感叹号(!)进行编码的问题【感叹号在URL编码中有特殊含义】
sysUser.password = sysUser.password.replace(/\!/g, '%21') // g表示全局替换
sysUser.passwordNew = sysUser.passwordNew.replace(/\!/g, '%21') // g表示全局替换
// 解决#号等特殊字符传输过程会被浏览器篡改的问题(如:ABCabc012@#)
sysUser.password = encodeURIComponent(sysUser.password)
sysUser.passwordNew = encodeURIComponent(sysUser.passwordNew)
return request({
url: `/${groupName}/modifyPassword`,
method: 'post',
data: sysUser
})
},
/**
* 设置密码
*/
setPassword(sysUser) {
// like12 find bug,20240605,解决前端encodeURIComponent默认不会对感叹号(!)进行编码的问题【感叹号在URL编码中有特殊含义】
sysUser.passwordNew = sysUser.passwordNew.replace(/\!/g, '%21') // g表示全局替换
// 解决#号等特殊字符传输过程会被浏览器篡改的问题(如:ABCabc012@#)
sysUser.passwordNew = encodeURIComponent(sysUser.passwordNew)
return request({
url: `/${groupName}/setPassword`,
method: 'post',
data: sysUser
})
},
// 登录的后端接口配置
export function login(data) {
// like12 find bug,20240605,解决前端encodeURIComponent默认不会对感叹号(!)进行编码的问题【感叹号在URL编码中有特殊含义】
data.password = data.password.replace(/\!/g, '%21') // g表示全局替换
// like12 add,20231207,登录接口禁止明文传输用户名密码,改为AES加密
data.username = encryptTool.encrypt(data.username)
data.password = encryptTool.encrypt(data.password)
// like12 find bug,20230518,解决IE兼容模式时中文用户名无法登录的问题 后端接收到为乱码
data.username = encodeURIComponent(data.username)
data.password = encodeURIComponent(encodeURIComponent(data.password))
/* // 原来是这样的
// like12 find bug,20230518,解决IE兼容模式时中文用户名无法登录的问题 后端接收到为乱码
data.username = encodeURIComponent(data.username) */
return request({
// like12 modified,20221004,拼接参数才行
url: '/xxx/xxx?grant_type=password&username=' + data.username + '&password=' + data.password,
method: 'post',
data
})
}