Java & J2EE Page 3 - Saving Client State with Cookies and Java |
CookieSetterServlet is one of the servlets you will find in the EAR. You can find the code for this servlet in Listing 1.
Listing 1: CookieSetterServlet.java The servlet grabs a parameter from the request named FavoriteCookiePreference. Note that the HTML file, favoritecookie.html calls the servlet and feeds the servlet with request data (see Figure 3).
Our code to create a cookie on the server side and send it back to the client is a straightforward process. We simply create a new Cookie object by calling the constructor with the name of the cookie we want to create and its associated value (the value we collected from our request). In the code, we also set a comment for the cookie. Finally, the resulting Cookie object is packaged to be shipped back to the client by calling the Response object’s addCookie method, which takes our new Cookie as an argument. For some visual feedback, the servlet reports to the user what was extracted from the request (see Figure 4).
Figure 4: Output of the CookieSetterServlet It is important to note that we added the cookie to our Response object before using our PrintWriter object. This order is mandatory if you want things to work. Your cookie is going to be sent back to the client as a header; headers must be written before accessing the PrintWriter. It is also important to note that the cookies that a server places on a client are associated only to that server. Coming up, we’ll use a different servlet to grab our cookie’s value from the client. Note that since this second servlet will reside on the same server as our first servlet, we are able to access the client cookie we established (which we named FavoriteCookieType).
blog comments powered by Disqus |