Developing JavaServer Pages

In this excerpt from chapter 4 of Joel Murach’s Java Servlets and JSP, you’ll learn how to develop a web application that consists of HTML pages and JavaServer Pages (JSPs). As you will see, JSPs work fine as long as the amount of processing that’s required for each page is limited. When you complete this chapter, you should be able to use JSPs to develop simple web applications of your own.

jspThe Email List Application

This topic introduces you to a simple web application that consists of one HTML page and one JavaServer Page, or JSP. Once you get the general idea of how this application works, you’ll be ready to learn the specific skills that you need for developing JSPs.

The User Interface for the Application

Figure 1 shows the two pages that make up the user interface for the Email List application. The first page is an HTML page that asks the user to enter a first name, last name, and email address. Then, when the user clicks on the Submit button, the HTML page calls the JSP and passes the three user entries to that page.

JSP pages
Figure 1: The user interface for the application
The HTML page

The JSP

JavaServer Pages

When the JSP receives the three entries, it could process them by checking them for validity, writing them to a file or database, and so on. In this simple application, though, the JSP just passes the three entries back to the browser so it can display the second page of this application. From this page, the user can return to the first page by clicking the Back button in the web browser or by clicking the Return button that’s displayed on this page.

Building Blocks

As simple as this application is, you’re going to learn a lot from it. In this chapter, you’ll learn how to enhance this application so it uses regular Java classes to save the user entries in a text file. Then, in later chapters, you’ll learn how to modify this application to illustrate other essential skills that apply to servlet and JSP programming.

Remember: this is from chapter four of Joel Murach’s Java Servlets and JSP (Mike Murach & Associates, ISBN 1890774189, 2003). Grab a copy at your favorite book store today!

Buy this book now.

{mospagebreak title=The Code for the HTML Page that Calls the JSP}

Figure 2 presents the code for the HTML page that calls the JSP. If you’ve read chapter 3, you shouldn’t have any trouble following it. Here, the Action attribute of the Form tag calls a JSP named show_email_entry.jsp that’s stored in the same directory as the HTML page, and the Method attribute specifies that the HTTP Get method should be used with this action. Then, when the user clicks on the Submit button, the browser will send a request for the JSP.

Figure 2: The code for the HTML page that calls the JSP

<!doctype html public “-//W3C//DTD HTML 4.0 Transitional//EN”>
<html>
 <head>
  <title>Chapter 4 – Email List application</title>
 </head>
   <body>
 <h1>Join our email list</h1>
   <p>To join our email list, enter your name and
     email address below. <br>
     Then, click on the Submit button.</p>

  <form action=”show_email_entry.jsp” method=”get”>
  <table cellspacing=”5″ border=”0″>
    <tr>
      <td align=”right”>First name:</td>
      <td><input type=”text” name=”firstName”></td>
    </tr>
    <tr>
      <td align=”right”>Last name:</td>
      <td><input type=”text” name=”lastName”></td>
    </tr>
    <tr>
      <td align=”right”>Email address:</td>
      <td><input type=”text” name=”emailAddress”></td>
    </tr>
    <tr>
      <td></td>
      <td><br><input type=”submit” value=”Submit”></td>
    </tr>
  </table>
  </form>
 </body>
</html>

You should also notice the Name attributes of the three text boxes that are used in the table within this HTML page. These are the names of the parameters that are passed to the JSP when the user clicks on the Submit button. In Figure 1, the parameter names are firstName, lastName, and emailAddress and the parameter values are John, Smith, and jsmith@hotmail.com.

Figure 3 presents the code for the JSP. As you can see, much of the JSP code is HTML. In addition, though, Java code is embedded within the HTML code in the form of JSP scriptlets and expressions. Typically, a scriptlet is used to execute one or more Java statements while a JSP expression is used to display text. To identify scriptlets and expressions, JSPs use tags. To distinguish them from HTML tags, you can refer to them as JSP tags.

Figure 3: The Code for the JSP

<!doctype html public “-//W3C//DTD HTML 4.0 Transitional//EN”>
<html>
 <head>
  <title>Chapter 4 – Email List application</title>
 </head>
<body>

< %
  String firstName = request.getParameter(“firstName”);
  String lastName = request.getParameter(“lastName”);
  String emailAddress = request.getParameter(“emailAddress”);
% >

<h1>Thanks for joining our email list</h1>
<p>Here is the information that you entered:</p>
  <table cellspacing=”5″ cellpadding=”5″ border=”1″>
    <tr>
      <td align=”right”>First name:</td>
      <td><%= firstName %></td>
    </tr>
    <tr>
      <td align=”right”>Last name:</td>
      <td><%= lastName %></td>
    </tr>
    <tr>
      <td align=”right”>Email address:</td>
      <td><%= emailAddress %></td>
    </tr>
  </table>

<p>To enter another email address, click on the Back <br>
button in your browser or the Return button shown <br>
below.</p>

  <form action=”join_email_list.html” method=”post”>
  <input type=”submit” value=”Return”>
  </form>

 </body>
</html>

Remember: this is from chapter four of Joel Murach’s Java Servlets and JSP (Mike Murach & Associates, ISBN 1890774189, 2003). Grab a copy at your favorite book store today!

 Buy this book now.

{mospagebreak title=Imitating HTML}

Description

Although a JSP looks much like an HTML page, a JSP contains embedded Java code. To code a scriptlet that contains one or more Java statements, you use the <% and %> tags. To display any expression that can be converted to a string, you use the <%= and %> tags.

When you code a JSP, you can use the implicit request object. This object is named request. You can use the getParameter method of the request object to get the values of the parameters that are passed to the JSP.

When you code a JSP, you can use the methods of the request object in your scriptlets or expressions. Since you don’t have to explicitly create this object when you code JSPs, this object is sometimes referred to as the implicit request object. The scriptlet in this figure contains three statements that use the getParameter method of the request object. Each of these statements returns the value of the parameter that is passed to the JSP from the HTML page. Here, the argument for each getParameter method is the name of the textbox on the HTML page.

Once the scriptlet is executed, the values for the three parameters are available as variables to the rest of the page. Then, the three expressions can display these variables. Since these expressions are coded within the HTML tags for a table, the browser will display these expressions within a table.

After the table, the JSP contains some HTML that defines a form. This form contains only one control, a submit button named Return. When it is clicked, it takes the user back to the first page of the application. If you have any trouble visualizing how this button or the rest of the page will look when displayed by a browser, please refer back to Figure 1.

As you read this book, remember that it assumes that you already know the basics of Java programming. If you have any trouble understanding the Java code in this chapter, you may need a refresher course on Java coding. To quickly review the basics of Java coding, we recommend that you use Murach’s Beginning Java 2 because it contains all the Java skills that you’ll need for working with this book. 

Remember: this is from chapter four of Joel Murach’s Java Servlets and JSP (Mike Murach & Associates, ISBN 1890774189, 2003). Grab a copy at your favorite book store today!

 Buy this book now.

{mospagebreak title=How to Create a JSP}

Now that you have a general idea of how JSPs are coded, you’re ready to learn some specific skills for creating a JSP. To start, you need to know more about coding scriptlets and expressions.

How to Code Scriptlets and Expressions

Figure 4 summarizes the information you need for coding scriptlets and expressions within a JSP. To code a scriptlet, for example, you code Java statements that end with semicolons within the JSP scriptlet tags. To code an expression, you code any Java expression that evaluates to a string. Since primitive data types like integers or doubles are automatically converted to strings, you can also use expressions that evaluate to these data types.

Figure 4: How to code scriptlets and expressions

The syntax for a JSP scriptlet

<% Java statements %>

The syntax for a JSP expression

<%= any Java expression that can be converted to a string %>

The syntax for getting a parameter from the implicit request object

request.getParameter(parameterName);

Examples that use scriptlets and expressions

A scriptlet and expression that display the value of the firstName parameter

<%
   String firstName = request.getParameter(“firstName”);
%>

The first name is <%= firstName %>.

An expression that displays the value of the firstName parameter

The first name is <%= request.getParameter(“firstName”) %>.

Two scriptlets and an expression that display an HTML line 5 times

<%
  int numOfTimes = 1;
  while (numOfTimes <= 5){
%>
  <h1> This line is shown <%= numOfTimes %%> of 5 times in a JSP.</h1>
<%
    numOfTimes++;
  }
%>

Description

Within a scriptlet, you can code one or more complete Java statements. Because these statements are Java statements, you must end each one with a semicolon.

Within a JSP expression, you can code any Java expression that evaluates to a string. This includes Java expressions that evaluate to any of the primitive types, and it includes any object that has a toString method. Because a JSP expression is an expression, not a statement, you don’t end it with a semicolon.

When you’re coding a scriptlet or an expression, you can use any of the methods of the implicit request object. In this figure, only the getParameter method is used, but you’ll learn about two more methods of the request object in the next figure.

In this figure, the first two examples show different ways that you can display the value of a parameter. The first example uses a scriptlet to return the value of the firstName parameter and store it in a String object. Then, this example uses an expression to display the value. In contrast, the second example uses an expression to display the value of the firstName parameter without creating the firstName object.

The last example in this figure shows how two scriptlets and an expression can be used to display an HTML line five times while a Java variable within the HTML line counts from 1 to 5. Here, the first JSP scriptlet contains the code that begins a while loop. Then, a line of HTML code uses a JSP expression to display the current value of the counter for the loop. And finally, the second scriptlet contains the code that ends the loop.

Remember: this is from chapter four of Joel Murach’s Java Servlets and JSP (Mike Murach & Associates, ISBN 1890774189, 2003). Grab a copy at your favorite book store today!

 Buy this book now.

{mospagebreak title=How to Use the Methods of the Request Object}

In the last figure, you learned how to use the getParameter method to return the value that the user entered into a textbox. Now, Figure 5 summarizes that method and illustrates it in a new context. This figure also summarizes and illustrates two more methods of the implicit request object.

Figure 5: How to use the methods of the request object

Three methods of the request object

Method

Description

getParameter(String param) Returns the value of the specified parameter as a string if it exists or null if it doesn’t. Often, this is the value defined in the Value attribute of the control in the HTML page or JSP.
getParameterValues(String param) Returns an array of String objects containing all of the values that the given request parameter has or null if the parameter doesn’t have any values.
getParameterNames() Returns an Enumeration object that contains the names of all the parameters contained in the request. If the request has no parameters, the method returns an empty Enumeration object.

More Scriptlets

A scriptlet that determines if a checkbox is checked


<%
    String rockCheckBox = request.getParameter(“Rock”);
    // returns the value or “on” if checked, null otherwise.
    if (rockCheckBox != null){
%>
        You checked Rock music!
<% 
    }
%>

A scriptlet that reads and displays multiple values from a list box

<%
    String[] selectedCountries = request.getParameterValues(“country”);
    // returns the values of items selected in list box.
    for (int i = 0; i < selectedCountries.length; i++){
%>
       <%= selectedCountries[i] %> <br>
<%
    }
%>

A scriptlet that reads and displays all request parameters and values

<%
    Enumeration parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()){
        String parameterName = (String) parameterNames.nextElement();
        String parameterValue = request.getParameter(parameterName);
%>
        <%= parameterName %> has value <%= parameterValue %>. <br>
<%
     }
%>

Description

You can use the getParameter method to return the value of the selected radio button in a group or the selected item in a combo box. You can also use it to return the value of a selected check box or independent radio button, but that value is null if it isn’t selected.

If an independent radio button or a checkbox doesn’t have a Value attribute, this method returns “on” if the control is selected or null if it isn’t.

In most cases, the getParameter method returns the value of the parameter. For a textbox, that’s usually the value entered by the user. But for a group of radio buttons or a combo box, that’s the value of the button or item selected by the user.

For checkboxes or independent radio buttons that have a Value attribute, the getParameter method returns that value if the checkbox or button is selected and a null value if it isn’t. For checkboxes or independent radio buttons that don’t have a Value attribute, though, the getParameter method returns an “on” value if the checkbox or button is selected and a null value if it isn’t. This is illustrated by the first example in this figure.

Remember: this is from chapter four of Joel Murach’s Java Servlets and JSP (Mike Murach & Associates, ISBN 1890774189, 2003). Grab a copy at your favorite book store today!

 Buy this book now.

{mospagebreak title=Retrieving Multiple Values}

To retrieve multiple values for one parameter name, you can use the getParameterValues method as illustrated by the second example. This method is useful for controls like list boxes that allow multiple selections. After you use the getParameterValues method to return an array of String objects, you can use a loop to get the values from the array.

To get the names of all the parameters sent with a request, you can use the getParameterNames method to return an Enumeration object that contains the names. Then, you can search through the Enumeration object to get the parameter names, and you can use the getParameter method to return the value for each parameter name. This is illustrated by the third example.

If you’re not familiar with the Enumeration class, you can learn more about it though the API. For most purposes, though, you only need to know that an Enumeration object is a collection that can be searched element by element. To determine if more elements exist in the collection, you can use the hasMoreElements method, which returns a boolean value. And to get the next element in the collection, you can use the nextElement method. 

Where and How to Save a JSP

As Figure 6 shows, you normally save the JSPs of an application in the same directory that you use for the HTML pages of the application. The difference is that the name for a JSP requires a jsp extension. So if you’re using a text editor that’s not designed for working with JSPs, you may have to place the filename in quotation marks to make sure the file is saved with the jsp extension.

Figure 6: Where and how to save a JSP

Where the Show_email_entry.jsp Page is Saved

c:tomcatwebappsmurachemail4

Other Places You Can Save Your JSPs

c:tomcatwebappsyourDocumentRoot
c:tomcatwebappsyourDocumentRootyourSubdirectory
c:tomcatwebappsROOT
c:tomcatwebappsROOTyourSubdirectory

A Standard Dialog Box for Saving a JSP

JavaServer Pages

Description

JSPs are normally saved in the same directory as the HTML pages. This directory should be a subdirectory of the web applications directory for your server. If you’re running Tomcat on your PC, that directory is usually c:tomcatwebapps or c:jakarta-tomcatwebapps.

For the first 16 chapters of this book, the document root directory for all applications is the murach directory. As a result, the HTML and JSP files for each application are stored in this directory or one of its subdirectories.

If you’re using Tomcat on your local system, you can also use webappsROOT as the root directory for your applications. The ROOT directory is automatically set up when you install Tomcat, and it is the default document root directory.

To make sure that the filename for a JSP is saved with the jsp extension when you’re using an HTML or text editor, you can enter the filename within quotes.

Like HTML pages, JSPs must be saved in a directory that’s available to the web server. For Tomcat 4.0, you can use any directory under the webapps directory. The root directory for the web applications that are presented in the first 16 chapters of this book is the webappsmurach directory, and the subdirectory for the Email List application that’s presented in this chapter is email4. Note, however, that you can also use the webappsROOT directory that Tomcat sets up as the default root directory. Or, you can create your own subdirectories under the webapps directory. 

Remember: this is from chapter four of Joel Murach’s Java Servlets and JSP (Mike Murach & Associates, ISBN 1890774189, 2003). Grab a copy at your favorite book store today!

 Buy this book now.

{mospagebreak title=How to Request a JSP}

After you create a JSP, you need to test it. One way to do that is to click on a link or a button on an HTML page that requests the JSP. Another way is to enter a URL into a web browser that requests the JSP. Figure 7 shows how to request a JSP either way.

Figure 7: How to request a JSP

A URL that includes parameters

JavaServer Pages

How Tomcat Maps Directories to HTTP Calls

Tomcat directory URL
c:tomcatwebappsmurach http://localhost:8080/murach/
c:tomcatwebappsmurachemail4 http://localhost:8080/murach/email4
c:tomcatwebappsROOT http://localhost:8080/
c:tomcatwebappsROOTemail4 http://localhost:8080/email4

A Form Tag that Requests a JSP

<form action=”show_email_entry.jsp” method=”get”>

Two URLs that Request a JSP

http://localhost:8080/murach/email4/show_email_entry.jsp
http://www.murach.com/email4/show_email_entry.jsp

How to Include Parameters

show_email_entry.jsp?firstName=John
show_email_entry.jsp?firstName=John&lastName=Smith

Description

When you use the Get method to request a JSP from an HTML form, the parameters are automatically appended to the URL.

When you code or enter a URL that requests a JSP, you can add a parameter list to it starting with a question mark and with no intervening spaces. Then, each parameter consists of its name, an equals sign, and its value. To code multiple parameters, use ampersands (&) to separate the parameters.

To request a JSP from an HTML form, you use the Action attribute of the form to provide a path and filename that point to the JSP. This is illustrated by the first example in this figure. Here, the assumption is that the HTML page and the JSP are in the same directory. If they weren’t, you would have to supply a relative or absolute path for the JSP file.

To request a JSP by entering its URL into a browser, you enter an absolute URL as shown by the next two examples in this figure. The first example shows the URL for the JSP when it’s stored on a local web server in the email4 directory of the murach directory. The second example shows the URL for the JSP if the JSP was deployed on the Internet server for www.murach.com.

When you test a JSP by entering a URL, you will often want to pass parameters to it. To do that, you can add the parameters to the end of the URL as shown by the last examples in this figure. Here, the question mark after the jsp extension indicates that one or more parameters will follow. Then, you code the parameter name, the equals sign, and the parameter value for each parameter that is passed, and you separate multiple parameters with ampersands (&). If you omit a parameter that’s required by the JSP, the getParameter method will return a null value for that parameter.

When you use a Get method to request a JSP from another page, any parameters that are passed to the JSP will be displayed in the browser’s URL address. In this figure, for example, you can see the first two parameters that have been attached to the URL. However, in the next figure, you’ll learn that the Post method works differently. 

Remember: this is from chapter four of Joel Murach’s Java Servlets and JSP (Mike Murach & Associates, ISBN 1890774189, 2003). Grab a copy at your favorite book store today!

 Buy this book now.

{mospagebreak title=Using Get and Post Methods}

When you code a Form tag that requests a JSP, you can code a Method attribute that specifies the HTTP method that’s used for the request. The Get method is the default HTTP method, but the Post method is also commonly used.

Figure 8 presents the pros and cons of using the Get and Post methods. With either method, you can still test the page by appending the parameters to the URL string. So the question really comes down to selecting the appropriate method for the finished web application.

Figure 8: When to Use the Get and Post Methods

An HTML form tag that uses the Post method

<form action=”show_email_entry.jsp” method=”post”>

A JSP Requested Through the Post Method

JavaServer Pages

When to Use the Get Method

  • If you want to transfer data as fast as possible.
  • If the HTML form only needs to transfer 4 KB of data or less.
  • If it’s okay for the parameters to be displayed in the URL.
  • If you want users to be able to include parameters when they bookmark a page.

When to Use the Post Method

  • If you’re transferring over 4 KB of data.
  • If it’s not okay for the parameters to be appended to the URL.

Description

The visible difference between the Get and Post methods is the URL that’s displayed in the browser. For Get requests from an HTML page, the parameters are appended to the URL. For Post requests, the parameters are still sent, but they’re not displayed in the browser.

You can test a JSP that uses either method by appending the parameters to the URL. 

Remember: this is from chapter four of Joel Murach’s Java Servlets and JSP (Mike Murach & Associates, ISBN 1890774189, 2003). Grab a copy at your favorite book store today!

 Buy this book now.

{mospagebreak title=Using the Post Method}

There are two primary reasons for using the Post method. First, since the Post method doesn’t append parameters to the end of the URL, it is more appropriate for working with sensitive data. If, for example, you’re passing a parameter for a password or a credit card number, the Post method prevents these parameters from being displayed in the browser. In addition, it prevents the web browser from including these parameters in a bookmark for a page. Second, you need to use the Post method if your parameters contain more than 4 KB of data.

For all other uses, the Get method is preferred. It runs slightly faster than the Post method, and it lets the user bookmark the page along with the parameters that were sent to the page.

How to Use Regular Java Classes with JSPs

In this topic, you’ll learn how to use regular Java classes to do the processing that a JSP requires. In particular, you’ll learn how to use two classes named User and UserIO to do the processing for the JSP of the Email List application.

The Code for the User and UserIO Classes

Figure 9 presents the code for a business class named User and an I/O class named UserIO. The package statement at the start of each class indicates where each class is stored. Here, the User class is stored in the business directory because it defines a business object while the UserIO class is stored in the data directory because it provides the data access for the application.

Figure 9: The Code for the User and UserIO Classes

The Code for the User Class

package business;

public class User{
    private String firstName;
    private String lastName;
    private String emailAddress;

    public User(){}

    public User(String first, String last, String email){
        firstName = first;
        lastName = last;
        emailAddress = email;
    }

    public void setFirstName(String f){
        firstName = f;
    }
    public String getFirstName(){ return firstName; }

    public void setLastName(String l){
        lastName = l;
    }
    public String getLastName(){ return lastName; }

    public void setEmailAddress(String e){
        emailAddress = e;
    }
    public String getEmailAddress(){ return emailAddress; }
}

The Code for the UserIO Class

package data;

import java.io.*;
import business.User;

public class UserIO{
    public synchronized static void addRecord(User user, String filename)throws IOException{
        PrintWriter out = new PrintWriter(
                          new FileWriter(filename, true));
        out.println(user.getEmailAddress()+ “|”
                    + user.getFirstName() + “|”
                    + user.getLastName());
        out.close();
   }
}

Note  The synchronized keyword in the declaration for the addRecord method of the UserIO class prevents two users of the JSP from using that method at the same time.

The User class defines a user of the application. This class contains three instance variables: firstName, lastName, and emailAddress. It includes a constructor that accepts three values for these instance variables. And it includes get and set methods for each instance variable.

In contrast, the UserIO class contains one static method named addRecord that writes the values stored in a User object to a text file. This method accepts two parameters: a User object and a string that provides the path for the file. If this file exists, the method will add the user data to the end of it. If the file doesn’t exist, the method will create it and add the data at the beginning of the file.

If you’ve read the first six chapters of Murach’s Beginning Java 2, you should understand the code for the User class. And if you’ve read chapters 16 and 17, you should understand the code in the UserIO class. The one exception is the use of the synchronized keyword in the addRecord method declaration. But this keyword just prevents two users from writing to the file at the same time, which could lead to an error. 

Remember: this is from chapter four of Joel Murach’s Java Servlets and JSP (Mike Murach & Associates, ISBN 1890774189, 2003). Grab a copy at your favorite book store today!

 Buy this book now.

{mospagebreak title=Managing Java Classes}

If you’re using Tomcat 4.0, Figure 10 shows where and how to save your compiled Java classes (the .class files) so Tomcat can access them. Usually, you’ll save your source code (the .java files) in the same directory, but that’s not required.

Figure 10: Where and How to Save and Compile Regular Java Classes

Where the User class is saved

c:tomcatwebappsmurachWEB-INFclassesbusiness

Where the UserIO class is saved

c:tomcatwebappsmurachWEB-INFclassesdata

Other places to save your Java classes

c:tomcatwebappsyourDocumentRootWEB-INFclasses
c:tomcatwebappsyourDocumentRootWEB-INFclassespackageName
c:tomcatwebappsROOTWEB-INFclasses
c:tomcatwebappsROOTWEB-INFclassespackageName

The DOS Prompt Window for Compiling the User Class

Command Prompt

Description

Although you can save the source code (the .java files) in any directory, you must save the class files (the .class files) in the WEB-INFclasses directory or one of its subdirectories. This can be subordinate to the ROOT directory or your own document root directory.

To compile a class, you can use TextPad’s Compile Java command, your IDE’s compile command, or the javac command from the DOS prompt window.

If you have trouble compiling a class, make sure your system is configured correctly as described in appendix A of my textbook.

The two paths shown at the top of this figure show where the User and UserIO classes that come with this book are saved. After that, the figure presents the syntax for other paths that can be used to store Java classes. If you review these paths, you’ll see that each one places the Java classes in a subdirectory of the WEB-INFclasses directory. 

Remember: this is from chapter four of Joel Murach’s Java Servlets and JSP (Mike Murach & Associates, ISBN 1890774189, 2003). Grab a copy at your favorite book store today!

 Buy this book now.

{mospagebreak title=Class Location}

Since the User class contains a package statement that corresponds to the business directory, it must be located in the WEB-INFclassesbusiness directory. In contrast, if the package statement specified “murach.email”, the compiled classes would have to be located in the WEB-INFclassesmurachemail directory.

Since TextPad is designed for working with Java, you can use it to compile regular Java classes. However, you may need to configure your system as described in appendix A of the text before it will work properly. In particular, you may need to add the appropriate WEB-INFclasses directory to your classpath.

If you use the DOS prompt window to compile your classes, you can do that as shown in this figure. Here, a DOS prompt is used to compile the User class. To start, the cd command changes the current directory to the WEB-INFclasses directory. Then, the javac command is used with “businessUser.java” as the filename. This compiles the User class and stores it in the business package, which is what you want.

A JSP that Uses the User and UserIO Classes

Figure 11 shows the code for the JSP in the Email List application after it has been enhanced so it uses the User and UserIO classes to process the parameters that have been passed to it. In the first statement of the body, a special type of JSP tag is used to import the business and data packages that contain the User and UserIO classes. You’ll learn how to code this type of tag in the next figure. For now, though, you should focus on the other shaded lines in this JSP.

Figure 11: A JSP that uses the User and UserIO classes

The code for a JSP that uses the User and UserIO classes

<!doctype html public “-//W3C//DTD HTML 4.0 Transitional//EN”>
<html>

<head>
  <title>Chapter 4 – Email List application</title>
</head>

<body>
<%@ page import=”business.*, data.*” %>
<%
    String firstName = request.getParameter(“firstName”);
    String lastName = request.getParameter(“lastName”);
    String emailAddress = request.getParameter(“emailAddress”);

    User user = new User(firstName, lastName, emailAddress);
    UserIO.addRecord(user, “../webapps/murach/WEB-INF/etc/UserEmail.txt”);
%>

<h1>Thanks for joining our email list</h1>

<p>Here is the information that you entered:</p>

  <table cellspacing=”5″ cellpadding=”5″ border=”1″>
    <tr>
      <td align=”right”>First name:</td>
      <td><%= user.getFirstName() %></td>
    </tr>
    <tr>
      <td align=”right”>Last name:</td>
      <td><%= user.getLastName() %></td>
    </tr>
    <tr>
      <td align=”right”>Email address:</td>
      <td><%= user.getEmailAddress() %></td>
    </tr>
  </table>

<p>To enter another email address, click on the Back <br>
button in your browser or the Return button shown <br>
below.</p>

<form action=”join_email_list.html” method=”post”>
  <input type=”submit” value=”Return”>
</form>

</body>
</html>

Description

This JSP uses a scriptlet to create a User object and add it to a file, and it uses JSP expressions to display the values of the User object’s instance variables.

Since the User and UserIO classes are stored in the business and data packages, the JSP must import these packages.

In the scriptlet of the JSP, the getParameter method is used to get the values of the three parameters that are passed to it, and these values are stored in String objects. Then, the next statement uses these strings as arguments for the constructor of the User class. This creates a User object that contains the three values. Last, this scriptlet uses the addRecord method of the UserIO class to add the three values of the User object to a file named UserEmail.txt that’s stored in the WEB-INFetc directory. Since the WEB-INFetc directory isn’t web-accessible, this prevents users of the application from accessing this file.

After the scriptlet, the code in the JSP defines the layout of the page. Within the HTML table definitions, the JSP expressions use the get methods of the User object to display the first name, last name, and email address values. Although these JSP expressions could use the String objects instead, the code in this figure is intended to show how the get methods can be used.

Conclusion

This tutorial is an excerpt from chapter 4 of Murach’s Java Servlets and JSP. If you had any trouble understanding the HTML presented in this excerpt, or if you had any trouble getting the Email List application to run under Tomcat, you may want to download chapters 1 through 3 of this book. Within those chapters, you’ll find an HTML tutorial, and you’ll find detailed instructions on how to install and configure the Tomcat servlet/JSP container.

On the other hand, if you want to learn more about working with JSPs, you may want to download chapter 4 in its entirety. The remainder of the chapter shows how to use three more types of JSP tags and how to work with JSP errors. And if you want to know more about servlets, you may want to download chapter 5 of this book. This chapter shows how to implement the Email List application using servlets. Once you learn how JSPs and servlets work separately, you can learn how to use the best features of each by using them together within the MVC pattern.

Remember: this is from chapter four of Joel Murach’s Java Servlets and JSP (Mike Murach & Associates, ISBN 1890774189, 2003). Grab a copy at your favorite book store today!

 Buy this book now.

Google+ Comments

Google+ Comments