- Using Hidden Controls
- The Cookie Class
- The HttpServletResponse Interface
- Creating a Cookie
- Reading a Cookie
- Setting and Reading a Cookie in the Same Page
- Using Sessions
- Creating a Session
- Setting Session Timeouts
- Using Applications
- Using Sessions, Applications, and JavaBeans
- Summary
- Q&A
- Workshop
Creating a Cookie
This next example will put all this new technology to work. Here, the code will create a cookie and place some text in it, and another page will read the cookie and display that text. To create the cookie, you use the Cookie class's constructor, passing it the name of the cookie (which will be message here) and the text in the cookie (which will just be "Hello!" in this case). You can also set the length of time the cookie will exist on the user's computer with the setMaxAge method, which you pass a value in seconds toto make the cookie last for a day, you can pass a value of 24 * 60 * 60 this way:
<HTML> <HEAD> <TITLE>Setting a Cookie</TITLE> </HEAD> <BODY> <H1>Setting a Cookie</H1> <% Cookie cookie1 = new Cookie("message", "Hello!"); cookie1.setMaxAge(24 * 60 * 60); %> . . .
That creates the cookie, but doesn't install it in the browserto do that, you use the response object's addCookie method this way:
<HTML> <HEAD> <TITLE>Setting a Cookie</TITLE> </HEAD> <BODY> <H1>Setting a Cookie</H1> <% Cookie cookie1 = new Cookie("message", "Hello!"); cookie1.setMaxAge(24 * 60 * 60); response.addCookie(cookie1); %> . . .
That installs the cookie in the browser. You can also include a link to the page that will read the cookie, as you see in Listing 7.2.
Listing 7.2 Setting a Cookie (ch07_02.jsp)
<HTML> <HEAD> <TITLE>Setting a Cookie</TITLE> </HEAD> <BODY> <H1>Setting a Cookie</H1> <% Cookie cookie1 = new Cookie("message", "Hello!"); cookie1.setMaxAge(24 * 60 * 60); response.addCookie(cookie1); %> <A HREF="ch07_03.jsp"/>Read the cookie</A> </BODY> </HTML>
You can see this page in Figure 7.3, where it's already set its cookie in the browser. The next step is to read that cookie's information back in.
Figure 7.3 Setting a cookie.