IT培训-高端面授IT培训机构
云和教育:云和数据集团高端IT职业教育品牌 全国咨询热线:0371-67988003
课程 请选择课程
    校区 请选择校区
      • 华为
        授权培训中心
      • 腾讯云
        一级认证培训中心
      • 百度营销大学
        豫陕深授权运营中心
      • Oracle甲骨文
        OAEP中心
      • Microsoft Azure
        微软云合作伙伴
      • Unity公司
        战略合作伙伴
      • 普华基础软件
        战略合作伙伴
      • 新开普(股票代码300248)
        旗下丹诚开普投资
      • 中国互联网百强企业锐之旗
        旗下锐旗资本投资
      当前位置:
      首页IT问答正文

      怎样在Cookie中存储中文?

      • 发布时间:
        2023-05-17
      • 版权所有:
        云和教育
      • 分享:

      Cookie不能存储中文,但是如果有这方面的需求,这个时候该如何解决呢?

      这个时候,我们可以使用之前学过的一个知识点叫URL编码,所以如果需要存储中文,就需要进行转码,具体的实现思路为:

      1.在AServlet中对中文进行URL编码,采用URLEncoder.encode(),将编码后的值存入Cookie中

      2.在BServlet中获取Cookie中的值,获取的值为URL编码后的值

      3.将获取的值在进行URL解码,采用URLDecoder.decode(),就可以获取到对应的中文值

      (1)在AServlet中对中文进行URL编码

      @WebServlet("/aServlet")
      public class AServlet extends HttpServlet {
          @Override
          protected void doGet(HttpServletRequest request, HttpServletResponse sponse) throws ServletException, IOException {
              //发送Cookie
              String value = "张三";
              //对中文进行URL编码
              value = URLEncoder.encode(value, "UTF-8");
              System.out.println("存储数据:" + value);
              //将编码后的值存入Cookie中
              Cookie cookie = new Cookie("username", value);
              //设置存活时间 ,1周 7天
              cookie.setMaxAge(60 * 60 * 24 * 7);
              //2. 发送Cookie,response
              response.addCookie(cookie);
          }
      
          @Override
          protected void doPost(HttpServletRequest request, HttpServletResponse 
      ponse) throws ServletException, IOException {
              this.doGet(request, response);
          }
      }

      (2)在BServlet中获取值,并对值进行解码。

      @WebServlet("/bServlet")
      public class BServlet extends HttpServlet {
          @Override
          protected void doGet(HttpServletRequest request, HttpServletResponse
      sponse) throws ServletException, IOException {
            //获取Cookie
            //1. 获取Cookie数组
            Cookie[] cookies = request.getCookies();
            //2. 遍历数组
            for (Cookie cookie : cookies) {
                //3. 获取数据
                String name = cookie.getName();
                if("username".equals(name)){
                    String value = cookie.getValue();//获取的是URL编码后的值
      %BC%A0%E4%B8%89
                    //URL解码
                    value = URLDecoder.decode(value,"UTF-8");
                    System.out.println(name+":"+value);//value解码后为 张三
                    break;
      
                }
            }
      
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse
      response) throws ServletException, IOException {
             this.doGet(request, response);
        }
      
      }

      至此,我们就可以将中文存入Cookie中进行使用。