Cookies in ServletA cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. How Cookie worksBy default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user. Types of CookieThere are 2 types of cookies in servlets.
Non-persistent cookieIt is valid for single session only. It is removed each time when user closes the browser. Persistent cookieIt is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or signout. Advantage of Cookies
Disadvantage of Cookies
Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.Cookie classjavax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies. Constructor of Cookie class
Useful Methods of Cookie classThere are given some commonly used methods of the Cookie class.
Other methods required for using Cookies
How to create Cookie?Let's see the simple code to create cookie. How to delete Cookie?Let's see the simple code to delete cookie. It is mainly used to logout or signout the user. How to get Cookies?Let's see the simple code to get all the cookies. Simple example of Servlet CookiesIn this example, we are storing the name of the user in the cookie object and accessing it in another servlet. As we know well that session corresponds to the particular user. So if you access it from too many browsers with different values, you will get the different value. index.htmlFirstServlet.javaSecondServlet.javaweb.xmldownload this example (developed using Myeclipse IDE) download this example (developed using Eclipse IDE) download this example (developed using Netbeans IDE) Output |