Cookies in Java PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document explains how cookies work in web applications, especially with Java programming. It demonstrates methods for using cookies in Java and provides code examples for working with cookies within web applications.
Full Transcript
Cookies are the textual information that is stored in key-value pair format to the client's browser during multiple requests. It is one of the state management techniques in session tracking. Basically, the server treats every client request as a new one so to avoid this situation cookies are used....
Cookies are the textual information that is stored in key-value pair format to the client's browser during multiple requests. It is one of the state management techniques in session tracking. Basically, the server treats every client request as a new one so to avoid this situation cookies are used. When the client generates a request, the server gives the response with cookies having an id which are then stored in the client's browser. Thus if the client generates a second request, a cookie with the matched id is also sent to the server. The server will fetch the cookie id, if found it will treat it as an old request otherwise the request is considered new. **Using Cookies in Java** - - - - - Few Methods used in Cookie class - - - - - **Methods required for using Cookies** +-----------------------------------------------------------------------+ | For adding cookie or getting the value from the cookie, we need some | | methods provided by | | | | other interfaces. They are: | | | | 1. **public void addCookie(Cookie ck)** method of | | HttpServletResponse interface is | | | | | | | | 2. **public Cookie\[\] getCookies()** method of HttpServletRequest | | interface is used | +-----------------------------------------------------------------------+ Cookie ck=**new** Cookie(\"user\",\"Minal Malhotra\"); //creating cookie object response.addCookie(ck); //adding cookie in the response **How to delete cookie** Cookie ck=**new** Cookie(\"user\",\"\");//deleting value of cookie ck.setMaxAge(0);//changing the maximum age to 0 seconds response.addCookie(ck);//adding cookie in the response if cookie's age is not set, by default age of a cookie is 30 minutes ### How to get Cookies? Let\'s see the simple code to get all the cookies. Cookie ck\[\]=request.getCookies(); **for**(**int** i=0;i\