Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

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

I am trying to set the unicode value inside the cookie but it doesn't accept this and throws Exception. I have checked the hexadecimal value of the string and it is correct but throws Exception while adding to a 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();
                }


            }
        }

    }

I get:

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

when adding the cookie to response object. I am using Tomcat 7 and Java 7 as the runtime environment.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Version 0 cookie values are restrictive in allowed characters. It only allows URL-safe characters. This covers among others the alphanumeric characters (a-z, A-Z and 0-9) and only a few lexical characters, including -, _, ., ~ and %. All other characters are invalid in version 0 cookies.

Your best bet is to URL-encode those characters. This way every character which is not allowed in URLs will be percent-encoded in this form %xx which is valid as cookie value.

So, when creating the cookie do:

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

And when reading the cookie, do:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...