What is cookie?

Cookie is a little piece of data(a name/value string pair) exchanged between client and server. The server sends the cookie to the client and it is stored in client side. When the client makes another request it returns the cookie.
You have to enable the cookie in your browser in order to work. By default cookie lives only as long as a session, once client closes the browser the cookie disappears. But you can also tell a cookie to stay alive even after the browser shut down. That way your web application can get the cookie information even though the session with the client is long gone.
There are different methods for cookie operation,

Javax.servlet.http.HttpServletRequest.getCookies();
Javax.servlet.http.HttpServletResponse.addCookie(Cookie cookie);
Javax.servlet.http.Cookie
getDomain()
getMaxAge():Returns the maximum specified age of the cookie.
getName()
getPath()
getSecure():Returns the value of the ‘secure’ flag.
getValue()
setDomain(String)
setMaxAge(int): Sets the maximum age of the cookie.
setPath(String)
setValue(String)

setSecure (Boolean flag):Indicates to the user agent that the cookie should only be sent using a secure protocol (https). This should only be set when the cookie’s originating server used a secure protocol to set the cookie’s value.

setComment: If a user agent (web browser) presents this cookie to a user, the cookie’s purpose will be described using this comment.

STEPS:

Creating a new cookie:
Cookie cookie=new Cookie(“username”,”bhabani”);
Setting how long cookie will live on the client:
Cookie.setMaxAge(30*60);// 30minutes
Sending cookie to client:
Response.addCookie(cookie);
Getting cookie from client request:
Cookie[] cookies=request.getCookies();
For(int i=0;i<cookies.length;i++){
Cookie cookie=cookies[i];
If(cookie.getName().equals(“username”)){
Out.println(“welcome back ”+cookie.getvalue());}
How many Cookies is supported to the host ?
Ans: User agents excepted to support twenty per host.And its take fourKilobytes each.

No comments:

Post a Comment