【问题标题】:java.lang.IllegalArgumentException: Control character in cookie value or attributejava.lang.IllegalArgumentException:cookie 值或属性中的控制字符
【发布时间】:2012-02-24 22:18:50
【问题描述】:

我正在尝试在 cookie 中设置 unicode 值,但它不接受并抛出异常。我检查了字符串的十六进制值,它是正确的,但是在添加到 cookie 时会抛出异常。

private void fnSetCookieValues(HttpServletRequest request,HttpServletResponse response) 
    {

        Cookie[] cookies=request.getCookies();
        for (int i = 0; i < cookies.length; i++) {

            System.out.println(""+cookies.length+"Name"+cookies[i].getName());

            if(cookies[i].getName().equals("DNString"))
            {   
                System.out.println("Inside if:: "+cookies[i].getValue()+""+cookies.length);
                try {

                    String strValue;
                    strValue = new String(request.getParameter("txtIIDN").getBytes("8859_1"),"UTF8");
                    System.out.println("Cookie Value To be stored"+strValue);
                    for (int j = 0; j < strValue.length(); j++) {

                        System.out.println("Code Point"+Integer.toHexString(strValue.codePointAt(j)));

                    }


                    Cookie ck = new Cookie("DNString",strValue);
                    response.addCookie(ck);

                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }
        }

    }

我明白了:

java.lang.IllegalArgumentException: Control character in cookie value or attribute.

将 cookie 添加到响应对象时。我使用 Tomcat 7 和 Java 7 作为运行时环境。

【问题讨论】:

    标签: java servlets cookies


    【解决方案1】:

    版本 0 cookie 值对允许的字符有限制。它只允许 URL 安全字符。这包括字母数字字符(a-z、A-Z 和 0-9)以及一些词汇字符,包括 -_.~%。版本 0 cookie 中的所有其他字符均无效。

    最好的办法是对这些字符进行 URL 编码。这样,URL 中不允许出现的每个字符都将被百分比编码为%xx,它作为 cookie 值有效。

    因此,在创建 cookie 时,请执行以下操作:

    Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
    // ...
    

    在读取 cookie 时,请执行以下操作:

    String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
    // ...
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 2017-10-16
      相关资源
      最近更新 更多