Sun Java Solaris Communities My SDN Account Join SDN
 
Tutorials & Code Camps

NO TITLE

 
[Top] [Prev] [Next] [Bottom]

Handling HTML Forms

One of the most common parts of an electronic commerce application is an HTML form in which a user enters some information. The information might be a customer's name and address, a word or phrase entered for a search engine, or a set of preferences gathered as market research data.

What Happens to the Form Data

The information the user enters in the form is stored in the request object, which is sent from the client to the JSP engine. What happens next?

FIGURE 1-2 represents how data flows between the client and the server (at least when you use Sun's JSP reference implementation; other JSP engines may work a little differently).

How Data is Passed Between the Client and the Server

The JSP engine sends the request object to whatever server-side component (JavaBeansTM component, servlet, or enterprise bean) the JSP file specifies. The component handles the request, possibly retrieving data from a database or other data store, and passes a response object back to the JSP engine. The JSP engine passes the response object to the JSP page, where its data is formatted according the page's HTML design. The JSP engine and Web server then send the revised JSP page back to the client, where the user can view the results in the Web browser. The communications protocol used between the client and server can be HTTP, or it can be some other protocol.

The request and response objects are always implicitly available to you as you author JSP source files. The request object is discussed in more detail later in this tutorial.

How To Create a Form

You typically define an HTML form in a JSP source file, using JSP tags to pass data between the form and some type of server-side object (usually a Bean). In general, you do the following things in your JSP application:

  1. Start writing a JSP source file, creating an HTML form and giving each form element a name.
  2. Write the Bean in a .java file, defining properties, get, and set methods that correspond to the form element names (unless you want to set one property value at a time explicitly).
  3. Return to the JSP source file. Add a <jsp:useBean> tag to create or locate an instance of the Bean.
  4. Add a <jsp:setProperty> tag to set properties in the Bean from the HTML form (the Bean needs a matching set method).
  5. Add a <jsp:getProperty> tag to retrieve the data from the Bean (the Bean needs a matching get method).
  6. If you need to do even more processing on the user data, use the request object from within a scriptlet.

The Hello, User example will make these steps more clear.

A Simple Hello Application

The JSP application shown in FIGURE 1-3 is very simple. It continues the illustrious computer science tradition know as Hello, World, but with a twist.

The User Enters a Name, and Then Duke Says Hello

Example Code

The Duke Banner (dukebanner.html)


<table border="0" width="400" cellspacing="0" cellpadding="0"> <tr> <td height="150" width="150"> &nbsp; </td> <td width="250"> &nbsp; </td> </tr> <tr> <td width="150"> &nbsp; </td> <td align="right" width="250">
<img src="duke.waving.gif"> </td> </tr> </table> <br>

The Main JSP File (hellouser.jsp)

<%@ page import="hello.NameHandler" %>

<jsp:useBean id="mybean" scope="page" 
class="hello.NameHandler" /> <jsp:setProperty name="mybean" property="*" /> <html> <head><title>Hello, User</title></head> <body bgcolor="#ffffff" background="background.gif"> <%@ include file="dukebanner.html" %> <table border="0" width="700"> <tr> <td width="150"> &nbsp; </td> <td width="550"> <h1>My name is Duke. What's yours?</h1> </td> </tr> <tr> <td width="150" &nbsp; </td> <td width="550"> <form method="get"> <input type="text" name="username" size="25"> <br> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </td> </tr> </form> </table> <% if ( request.getParameter("username") != null ) { %> <%@ include file="response.jsp" %> <% } %> </body> </html>

The Response File (response.jsp)

<table border="0" width="700">
<tr>
<td width="150"> &nbsp; </td>

<td width="550">

<h1>Hello, <jsp:getProperty name="mybean" 
        property="username" />!
</h1>

</td>
</tr>
</table>

The Bean That Handles the Form Data (namehandler.java)

package hello;

public class NameHandler {

    private String username;

    public NameHandler() { 
        username = null;
    }

    public void setUsername( String name ) {
        username = name;
    }

          public String getUsername() { 
        return username;
    }
}

Constructing the HTML Form

An HTML form has three main parts: the opening and closing <form> tags, the input elements, and the Submit button that sends the data to the server. In an ordinary HTML page, the opening <form> tag usually looks something like this:

<form method=get action=someURL>

In other Web applications, the action attribute specifies a CGI script or other program that will process the form data. In a JSP file, you can omit the action attribute if you want the data sent to the Bean specified in the <jsp:useBean> tag or specify another JSP file.

The rest of the form is constructed just like a standard HTML form, with input elements, a Submit button, and perhaps a Reset button. Be sure to give each input element a name, like this:

<input type="text" name="username">

Using the GET and POST Methods

The HTTP GET and POST methods send data to the server. In a JSP application, GET and POST send data to the Bean, servlet, or other server-side component that is handling the form data.

In theory, GET is for getting data from the server and POST is for sending data there. However, GET appends the form data (called a query string) to an URL, in the form of key/value pairs from the HTML form, for example, name=John. In the query string, key/value pairs are separated by & characters, spaces are converted to + characters, and special characters are converted to their hexadecimal equivalents. Because the query string is in the URL, the page can be bookmarked or sent as email with its query string. The query string is usually limited to a relatively small number of characters.

The POST method, however, passes data of unlimited length as an HTTP request body to the server. The user working in the client Web browser cannot see the data that is being sent, so POST requests are ideal for sending confidential data (such as a credit card number) or large amounts of data to the server.

Writing the Bean

If your JSP application uses a Bean, you can write the Bean according to the design patterns outlined in the JavaBeans API Specification, remembering these general points:

  • If you use a <jsp:getProperty> tag in your JSP source file, you need a corresponding get method in the Bean.
  • If you use a <jsp:setProperty> tag in your JSP source file, you need one or more corresponding set methods in the Bean.

Setting properties in and getting properties from a Bean is explained a bit more in the next section.

Getting Data From the Form to the Bean

Setting properties in a Bean from an HTML form is a two-part task:

  • Creating or locating the Bean instance with <jsp:useBean>
  • Setting property values in the Bean with <jsp:setProperty>

The first step is to instantiate or locate a Bean with a <jsp:useBean> tag before you set property values in the Bean. In a JSP source file, the <jsp:useBean> tag must appear above the <jsp:setProperty> tag. The <jsp:useBean> tag first looks for a Bean instance with the name you specify, but if it doesn't find the Bean, it instantiates one. This allows you to create a Bean in one JSP file and use it in another, as long as the Bean has a large enough scope.

The second step is to set property values in the Bean with a <jsp:setProperty> tag. The easiest way to use <jsp:setProperty> is to define properties in the Bean with names that match the names of the form elements. You would also define corresponding set methods for each property. For example, if the form element is named username, you would define a property username property and methods getUsername and setUsername in the Bean.

If you use different names for the form element and the Bean property, you can still set the property value with <jsp:setProperty>, but you can only set one value at a time. For more information on the syntax variations of <jsp:setProperty>, see the JavaServer Pages Syntax Card.

Checking the Request Object

The data the user enters is stored in the request object, which usually implements javax.servlet.HttpServletRequest (or if your implementation uses a different protocol, another interface that is subclassed from javax.servlet.ServletRequest).

You can access the request object directly within a scriptlet. Scriptlets are discussed in more detail in Tutorial 2, but for now it's enough to know that they are fragments of code written in a scripting language and placed within <% and %> characters. In JSP 1.0, you must use the JavaTM programming language as your scripting language.

You may find some of these methods useful with the request object:


Method


Defined In


Job Performed


getRequest


javax.servlet.jsp.PageContext


Returns the current request object


getParameterNames


javax.servlet.ServletRequest


Returns the names of the parameters request currently contains


getParameterValues


javax.servlet.ServletRequest


Returns the values of the parameters request currently contains


getParameter


javax.servlet.ServletRequest


Returns the value of a parameter if you provide the name

You'll find other methods as well, those defined in ServletRequest, HttpServletRequest, or any subclass of ServletRequest that your implementation uses.

The JSP engine always uses the request object behind the scenes, even if you do not call it explicitly from a JSP file.

Getting Data from the Bean to the JSP Page

Once the user's data has been sent to the Bean, you may want to retrieve the data and display it in the JSP page. To do this, use the <jsp:getProperty> tag, giving it the Bean name and property name:

<h1>Hello, <jsp:getProperty name="mybean" property="username"/>!

The Bean names you use on the <jsp:useBean>, <jsp:setProperty>, and <jsp:getProperty> tags must match, for example:

hellouser.jsp:
<jsp:useBean id="mybean" scope="session" class="hello.NameHandler" / >
<jsp:setProperty name="mybean" property="*" />

response.jsp:
<h1>Hello, <jsp:getProperty name="mybean" property="username"/>!

In this example, the tags are in two files, but the Bean names still must match. If they don't, the Sun JSP reference implementation throws an error, possibly a fatal one.

The response the JSP engine returns to the client is encapsulated in the implicit response object, which the JSP engine creates.

How to Run the Example

The instructions given here use a UNIX-style pathname. If you are working on Windows, use the same pathname with the proper separator.

1

Create the directory (or folder) ../jswdk-1.0/examples/jsp/tutorial/hellouser.

2

Place the following files in the ../tutorial/hellouser directory: background.gif, duke.waving.gif, dukebanner.html, hellouser.jsp, and response.jsp.

3

Create the directory (or folder) ../jswdk-1.0/examples/WEB-INF/jsp/beans/hello. Note that this directory is named hello, not hellouser.

4

Place the files NameHandler.java and NameHandler.class in the ../beans/hello directory.

5

Start the Sun JSP reference implementation:
cd ../jswdk-1.0
startserver

6

Open a Web browser and go to
http://yourMachineName:8080/examples/jsp/tutorial/hellouser/hellouser.jsp

More Info

  • Using Beans in JSP Applications chapter

[Top] [Prev] [Next] [Bottom]

Copyright © 1999, Sun Microsystems, Inc. All rights reserved.