Throwing JavaScript Into the (Cookie Dough) Mix - Java
Cookies serve as a facility for servers to send information to a client. This information is then housed on the client, from which the server can later retrieve the information. In this article, we will study the concept of saving client state with cookies using Java Servlets. I’ll walk you through an end to end example where you will store and retrieve data using cookies.
Since our cookies are stored on our client, our client Internet browser can access them using JavaScript. We do just that in the file grabcookievaluewithjavascript.html whose code is shown in Listing 3 below.
function ReportCookieValue (cookieName) { var arg = cookieName + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) {
var j = i + alen; var sub = document.cookie.substring(i,j); if (sub == arg) { return GetCookieValue(j); } else i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break;
} return null; } // --> </SCRIPT> </HEAD> <BODY> <p></p> <h2>According to JavaScript, you like <script language="JavaScript">
The output of our JavaScript cookie extraction is shown below:
Figure 6: Extracting our Cookie Value on the Client via JavaScript
Being able to access your cookies via JavaScript represents a powerful functionality. By doing this, you can have forms preloaded with what is resident in client cookie data. As an exercise, you should try and modify favoritecookie.html to initially present the pull down value that was resident in your cookie.