Saturday, 11 March 2017

J2EE: What are cookies?

Cookies are nothing more than a little piece of data (name/value String pairs) exchanged between client and server. Server sends the cookie to the client, and the client returns the cookie when the client makes another request.

Cookies don't require user interaction, the cookie exchange is automatic. A session cookie lives only as long as session, once the client quits his browser, the cookie disappears. That's how "JSESSIONID" cookie works. But you can tell a cookie to stay alive even after the browser shuts down.

How to get the cookies from HttpServletRequest?

getCookies() method returns all the cookies present in request header. There is not getCookie() method.

How to add a cookie to HttpServletResponse?

addCookie() method adds the cookie to response header.

How to create a cookie?

You can do everything with cookie with the help of Cookie class. for creating a new cookie

Cookie cookie = new Cookie("username", "Sreenath");
cookie.setMaxAge(30*60); // in secods.

setting max age to -1 makes the cookie disappear when the browser exits. So calling getMaxAge() on "JSESSIONID" cookie returns -1.








0 comments:

Post a Comment

Note: only a member of this blog may post a comment.