解决 Cookie 中文存储异常

    xiaoxiao2025-07-07  7

    在开发过程中,我采用 Cookie 存储了一些中文字符,但是读取的时候老是为空,最后感觉是编码问题,就自己手动搜了下,最后解决了,在这里分享给大家。

    存储时候进行转码

    //对含有中文字符的Cookie进行转码 String data = java.net.URLEncoder.encode(request.getParameter("data"),"UTF-8"); //存储Cookie Cookie cookie = new Cookie(request.getParameter("currentTime"), data ); //设置Cookie存活时间 cookie.setMaxAge(5); //将Cookie添加到本地 ServletActionContext.getResponse().addCookie(cookie);

    请注意:一定要采用 UTF-8,本人采用 GBK 依然存在问题

    读取的时候进行解码

    //获取 request 对象 request = ServletActionContext.getRequest(); // 获取 Cookie 数组 Cookie[] cookies = request.getCookies(); String param = null; // 遍历数组,得到数据 for(Cookie cookie : cookies){ if(cookie.getName().equals(request.getParameter("currentTime"))){ param = cookie.getValue(); //进行解码 param = URLDecoder.decode(param, "UTF-8"); } }

    总结:主要就是以下两个步骤:

    对存入 Cookie 中的数据进行编码从 Cookie 中的数据解码
    转载请注明原文地址: https://ju.6miu.com/read-1300449.html
    最新回复(0)