Cookie and it's use

The website uses cookies. By using the website and agreeing to this policy, you consent to our use of cookies in accordance with the terms of this policy.

What is Cookie ?

Cookies are a mechanism that a servlet uses to have clients hold a small amount of state-information associated with the user. Servlets can use the information in a cookie as the user enters a site (as a low-security user sign-on, for example), as the user navigates around a site (as a repository of user preferences for example), or both.

Handling All Browsers through Cookie

By default, session tracking uses cookies to associate a session identifier with a user. To also support users that access a servlet with a browser that does not support cookies, or that is set up to reject cookies, you must use URL rewriting instead.

When you use URL rewriting you call methods that, when necessary, include the session ID in a link. You must call these methods for every link in the servlet response. The method that associates a session ID with a URL is HttpServletResponse.encodeURL. If you redirect the user to another page, the method to associate the session ID with the redirected URL is called


The URL encoding and encoding redirect methods decide whether the URL needs to be rewritten, and return the URL either changed or unchanged. (The rules for URLs and redirected URLS differ, but in general if the server detects that the browser supports cookies, then the URL is not rewritten.)

The version of the Duke's Bookstore example that uses URL rewriting has the following code in
//Print out info on each book in its own two rows
out.println(" " + ...
response.encodeURL("/bookstore/bookdetails?bookId=" +
bookId) +
"\"> " + books[i].getTitle() +"
" + ..."
response.encodeURL("/bookstore/catalog?Buy=" + bookId)
+ "\"> Add to Cart
" +
Notice that the CatalogServlet returns two links to the user for each book. One link offers details about the book and the other allows you to add the book to your shopping cart. Both URLs would be rewritten because, again, every link that the servlet returns to the user must be rewritten when URL rewriting is used.

If the user clicks on a link with a rewritten URL, the servlet recognizes and extracts the session ID. Then the getSession method uses the session ID to get the user's HttpSession object.

On the other hand, if the user's browser does not support cookies and the user clicks on an un-rewritten URL, the user's session is lost. The servlet contacted through that link creates a new session, but the new session does not have the data associated with the previous session. Once a servlet loses the session data, the data is lost for all servlets that share the session. You should consistently use URL rewriting if your servlet is to support clients that do not support or accept cookies.

Importance of Cookies

Cookies are a way for a server (or a servlet, as part of a server) to send some information to a client to store, and for the server to later retrieve its data from that client. Servlets send cookies to clients by adding fields to HTTP response headers. Clients automatically return cookies by adding fields to HTTP request headers.

Each HTTP request and response header is named and has a single value. For example, a cookie could be a header named BookToBuy with a value 304qty1, indicating to the calling application that the user wants to buy one copy of the book with stock number 304. (Cookies and their values are application-specific.) Multiple cookies can have the same name. For example, a servlet could send two cookies with headers named BookToBuy; one could have the value shown previously, 304qty1, while the other could have a value 301qty3.

These cookies would indicate that the user wants to buy one copy of the book with stock number 304, and three copies of the book with stock number 301.

In addition to a name and a value, you can also provide optional attributes such as comments. Current web browsers do not always treat the optional attributes correctly, so you should not rely on them.
A server can provide one or more cookies to a client. Client software, such as a web browser, is expected to support twenty cookies per host, of at least four kilobytes each.

When you send a cookie to a client, standard HTTP/1.0 caches will not cache the page. Currently, the
javax.servlet.http.Cookie does not support HTTP/1.1 cache control models.

Cookies that a client stores for a server are returned by the client to that server and only that server. A server can contain multiple servlets; the Duke's Bookstore example is made up of multiple servlets running within a single server. Because cookies are returned to a server, servlets running within a server share cookies.

The examples in this section illustrate this by showing the CatalogServlet and ShowCart servlet working with the same cookies.

Creating a Cookie

The constructor for thejavax.servlet.http.Cookie class creates a cookie with an initial name and value.
You can change the value of the cookie later with its setValue method.

The value of the cookie can be any string, though null values are not guaranteed to work the same way on all browsers. In addition, if you are sending a cookie that complies with Netscape's original cookie specification, do not use whitespace or any of these characters:

[ ] ( ) = , " / ? @ : ;

If your servlet returns a response to the user with a Writer, create the cookie before accessing the Writer.(Because cookies are sent to the client as a header, and headers must be written before accessing the Writer.)

If the CatalogServlet used cookies to keep track of a client's book order, the servlet could create cookies likethis:

//If the user wants to add a book, remember it by adding a cookie
if (bookId != null) {
Cookie getBook = new Cookie("Buy", bookId);

advance java study material

Setting Cookie Attributes

The Cookie class provides a number of methods for setting a cookie's values and attributes. Using these methods is straightforward; they are explained in the javadoc for Cookie class.

The following example sets the comment field of the CatalogServlet's cookie. The comment field describes the purpose of the cookie.

getBook.setComment("User wants to buy this book " + "from the bookstore.");

You can also set the maximum age of the cookie. This attribute is useful, for example, for deleting a cookie. Once again, if Duke's Bookstore kept track of a user's order with cookies, the example would use this attribute to delete a book from the user's order. The user removes a book from the shopping cart in the ShowCartServlet; its code would look something like this:


Sending the Cookie

Cookies are sent as headers of the response to the client; they are added with the addCookie method of the HttpServletResponse class. If you are using a Writer to return text data to the client, you must call the
addCookie method before calling the HttpServletResponse's getWriter method.
Continuing the example of the CatalogServlet, the following is code for sending the cookie:

Retrieving Cookies
Clients return cookies as fields added to HTTP request headers. To retrieve any cookie, you must retrieve all the cookies using the getCookies method of the HttpServletRequest class.

// Find the cookie that pertains to the book to remove
Cookie[] cookies = request.getCookies();

// Delete the book's cookie by setting its maximum age to zero

Getting the Value of a Cookie

To find the value of a cookie, use its getValue method. To continue the ShowCartServlet example:

Cookie[] cookies = request.getCookies();

for(i=0; i < cookies.length; i++) {
Cookie thisCookie = cookie[i];
if (thisCookie.getName().equals("Buy") &&
thisCookie.getValue().equals(bookId)) {

// Delete the cookie by setting its maximum age to zero

thisCookie.setMaxAge(0); } }

Keywords: Cookie, Getting the cookie value, cookie attributes, how to create a cookie, definition of cookie, why use cookie,cookie value



advance-java,2,advancejava,1,aktu entrance exam,1,aktu exam schedule,1,ASP,1,bare machine,1,base register and limit register,1,Basic Computer network questions,1,C Programming,15,C Plus Plus,1,C Programming,2,C Programming MCQ,2,C Programming Questions,2,C programming study material for gate exam,13,CBNST Program,1,Childcare,1,CJ,2,Cloud Computing,1,components of use case diagram,1,Computer architecture based questions for gate exam,11,Computer Network,3,Computer Network Study Material,4,Computer network study material for gate,2,Computer Networks,7,Computer Science Study Material for Gate,20,computer science study material for gate exam,37,content based image retrieval content based image retrieval system,1,contiguous memory allocation,2,Core Java,8,COre Java Interview Questions,1,core java interviews questions,1,cyber crime report,1,Cyber crime status,1,cybercrime and security,1,cybercrime examples,1,Data link Layer Questions,1,Data Mining,1,Data Structure Questions,1,Data Transmission Architecture,1,Data Transmission in wsn,1,DBMS,4,dbms question paper,1,DE,1,Different types of addressing modes,1,Digital Electronics,1,DS,1,dynamic linking,1,dynamic linking in memory management,1,Electroencephalogram,1,file concept in os,1,File Handling,1,file management in operating system,1,FOC,1,Fundamenatl of Computer,1,Gate 2017,5,Gate 2017 Admit card,1,Gate 2017 Exam Schedule,1,Gate 2017 Syllabus,1,gate 2018,1,gate cse study material,1,gate practice set,10,gate study material for computer science,19,Gate study material for computer science 2017,1,GatePreviousYear,1,General,3,HCL Aptitude Test,1,HR Interview Questions,1,HTML,1,Image Processing,1,Important Date of Gate 2017 Exam,1,Information Security Policy,1,internal and external fragmentation,1,JS,1,lagrange's interpolation formula,1,lagrange's interpolation formula examples,1,Looping in C,1,MComputing,1,memory fragmentation,1,memory management,1,Motivational,4,NCER,2,Numerical Techniques Lab,1,OOT,1,Operating System,9,Operating System Objective Questions,4,Operating System Questions Bank,1,Operating system questions for gate,1,Operating System Study material,2,operating system study material for gate exam,17,Operating system tutorial,3,ORACLE,1,page swapping,1,paged memory allocation,1,paged memory allocation in operating system,1,paging technique of memory management .paging technique,1,paging technique of memory management program in c,1,Pointer in C,5,Process based question for gate,1,Quiz on non conventional energy resources,1,Regression testing,1,relocation in memory management,1,relocation registe,1,relocation register,1,resident monitor,1,resident monitor in operating system,1,routing table,1,segmentation in memory management,1,segmentation in memory management in operating system,1,Servlet,1,session tracking,1,session tracking in java,1,session tracking in servlet,1,Software Engineering,7,Software Engineering baes study material for gate,1,software engineering interview questions,1,Software Quality Assurance,3,SPM,1,SQL,1,Structure in C,1,Study Material for gate Computer Science,11,swapping in memory management,1,swapping in operating system,1,TCS Code Vita,1,Technical Questions from DBMS,1,Thrashing in os,1,Threads concept in operating system,1,Tips to Learn Coding,1,Top 30 Core Java Interview Questions with Answer,2,top down approach,1,top down approach in programming,1,Types of operating system,1,UML,1,use case diagram explanation,1,website uses cookies,1,what is cookies website,1,What is process control block ?,1,Wireless Sensor Network,3,worst fit algorithm for memory allocation,1,XML,1,
Computer Science Junction: Cookie and it's use
Cookie and it's use
The website uses cookies. By using the website and agreeing to this policy, you consent to our use of cookies in accordance with the terms of this policy.
Computer Science Junction
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share. STEP 2: Click the link you shared to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy