Workshop 6. The Response Object
Objective
The aim of this workshop is to create a cookie cutter JSP that creates cookies.
Time Available
This workshop should take no longer than 60 minutes.
Response Object Workshop
The following demonstrates the objective of this workshop.
- Download the file 'CookieCutter.txt' from the following hyperlink and save it to your
working directory. Change extension from 'txt' to 'jsp'.
- Open this file in your editor.
This file already contains some code that displays a table of all cookies that are currently registered by the web server on the client machine. Read this code and make sure you understand what is going on. Below this table is a form that allows the user to provide a name and value for a cookie. This form sends this data to 'makecookie.jsp' which is the JSP we are going to write.
- Create a new JSP called 'makeCookie.jsp' and add the following HTML.
<HTML> <HEAD> <TITLE>JSP Course - Request Workshop</TITLE> </HEAD> <BODY> <P><%= strMsg %></P> <P>Click back in your browser to view previous form, select refresh and see if your new cookie has indeed been created.</P> </BODY> </HTML>
- Before the opening
<HTML>statement add a new script block. Here we will add the code to create a cookie. As part of this process we want to updatestrMsgwith a message to say that either the cookie was successfully created or if there was a problem.
- First add the following code that defines this variable and picks up the form data,
String strMsg; String strCookieName = request.getParameter("CookieName"); String strCookieValue = request.getParameter("CookieValue"); - Now as always with form data we need to make sure that the data is neither null nor empty.
Add the following to check
strCookieNameif((strCookieName!=null) &&(!strCookieName.equals(""))) { } else { strMsg = "Must provide a cookie name."; } - In the true part add a similar
if..elsestatement to checkstrCookieValue.
- In the true part of this statement we want to create the cookie,
Cookie c = new Cookie(strCookieName,strCookieValue); response.addCookie(c); strMsg = "Cookie successfully created.";
- Save and test your work.
More Implicit Objects
The next section looks at the session and application objects