解决Get请求传参中文乱码问题

解决Get请求传参中文乱码问题

观前提示:

本文所使用的IDEA版本为ultimate 2019.1,JDK版本为1.8.0_141,Tomcat版本为9.0.12。

在前几天项目中,在使用get发送url请求传参中文时,出现了乱码,上网找了一下原因后,提供了以下解决方案。

1.encodeURI

1.1 前端

前端jsp页面部分代码如下

<script type="text/javascript">
    function doSubmit(){
     
     
        var url = "${pageContext.request.contextPath}/test/testEncodeURI"
            + "?userName=" + encodeURI(encodeURI("张三"));
        window.location.href = url;
    }
</script>

1.2 后台

后台测试Controller如下

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;

/**
 * 测试Controller
 * @author jjy
 * @date 2020-07-21
 */
@Controller
@RequestMapping("/test")
public class TestController {
    
    

    /**
     * 测试encodeURI
     * @param request
     * @return
     */
    @RequestMapping("testEncodeURI")
    public String testEncodeURI(HttpServletRequest request){
    
    
        String userName = request.getParameter("userName");
        System.out.println("Before encodeURI : " + userName);
        try {
    
    
            userName = URLDecoder.decode(userName, "UTF-8");
        } catch (Exception e){
    
    
            e.printStackTrace();
        }
        System.out.println("After encodeURI : " + userName);
        return "index";
    }
}

运行结果如下
在这里插入图片描述

1.3 总结

  1. 编码解码流程如下:
    UTF-8编码->UTF-8(iso-8859-1)编码->iso-8859-1解码->UTF-8解码,编码和解码的过程是对称的,所以不会出现乱码。

  2. 前端两次encodeURI:
    encodeURI函数采用utf-8进行编码,而在服务器的进行解码时候,默认都不是以uft-8进行解码,所以就会出现乱码。
    两次encodeURI,第一次编码得到的是UTF-8形式的URL,第二次编码得到的依然是UTF-8形式的URL,但是在效果上相当于首先进行了一 次UTF-8编码(此时已经全部转换为ASCII字符),再进行了一次iso-8859-1编码,因为对英文字符来说UTF-8编码和ISO- 8859-1编码的效果相同。

  3. 后台解码:
    在后台接收参数时候,首先通过request.getParameter()自动进行第一次解码(可能是 gb2312,gbk,utf-8,iso-8859-1等字符集,对结果无影响)得到ascii字符,然后再使用UTF-8进行第二次解码,通常使用 java.net.URLDecoder("",“UTF-8”)方法。

猜你喜欢

转载自blog.csdn.net/weixin_43611145/article/details/108826778