URLEncoder和URLDecoder;cookie中保存特殊字符以及URL中乱码问题解决方案

版权声明:本站所提供的文章资讯、软件资源、素材源码等内容均为本作者提供、网友推荐、互联网整理而来(部分报媒/平媒内容转载自网络合作媒体),仅供学习参考,如有侵犯您的版权,请联系我,本作者将在三个工作日内改正。 https://blog.csdn.net/weixin_42323802/article/details/83005095

cookie的特殊字符的编码和解码来解决乱码问题; 

 编码:

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //
        String str="hello   world";
        String str1 = URLEncoder.encode(str, "utf-8");// 把str 编码为str1
        Cookie cookie = new Cookie("str1", str1);        //保存在cookie响应给浏览器
        response.addCookie(cookie);   //在另一个servlet中解码
    }

 解码:

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("str1")) {  //找到 str1 的cookie
                String decode = URLDecoder.decode(cookie.getValue(), "utf-8");
                System.out.println(decode);
                response.getWriter().print(decode);   //显示在页面
            }
        }
    }

首先访问编码,然后访问解码,结果在浏览器中显示;

猜你喜欢

转载自blog.csdn.net/weixin_42323802/article/details/83005095
今日推荐