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.

Demo

  1. Download the file 'CookieCutter.txt' from the following hyperlink and save it to your working directory. Change extension from 'txt' to 'jsp'.

    Download file icon
  2. 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.

  3. 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>
    
    
  4. 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 update strMsg with a message to say that either the cookie was successfully created or if there was a problem.

  5. 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");
    
  6. Now as always with form data we need to make sure that the data is neither null nor empty. Add the following to check strCookieName
    if((strCookieName!=null)
        &&(!strCookieName.equals("")))
    {
    
    }
    else
    {
      strMsg = "Must provide a cookie name.";
    }
    
  7. In the true part add a similar if..else statement to check strCookieValue.

  8. 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.";
    
  9. Save and test your work.

If you couldn't get your solution to work then click the icon to display the source code. Source code icon

More Implicit Objects

The next section looks at the session and application objects

Back Next