Why cookie object in JSP can contain just value of type String?

Viewed 85

As a beginner in JSP I noticed that we can hold any value inside of a session, while cookie can have value only of type String. I found it weird because what if someone wants to hold type other than String in Cookie?

  • Session:

setAttribute(String name, Object value)

Binds an object to this session, using the name specified.

  • Cookie:

Cookie(String name, String value)

Constructs a cookie with a specified name and value.

Can someone from community help me understand it? Why we can't store anything inside Cookie except String, while we can inside Session's labels?

Or from a different perspective, why should cookie hold only String value?

1 Answers

Because a cookie is specified by RFC 6265 to store literal string values for a web browser to send as part of the HTTP request header.

From the linked RFC,

cookie-header = "Cookie:" OWS cookie-string OWS
cookie-string = cookie-pair *( ";" SP cookie-pair )

tl;dr cookie(s) are part of (and specified by) web protocols (not Java).

Related