|[ Team LiB ]|
A Simple HTML Form
To start off the exploration of HTML forms, it's best to start with a small form and expand from there. Also, it's better to start with a JSP rather than a servlet, because it is easier to write out the HTML. Most of the form handling for JSPs and servlets is identical, so after you know how to retrieve form information from a JSP, you know how to do it from a servlet. Listing 3.1 shows an HTML file containing a simple input form that calls a JSP to handle the form.
<html> <body> <h1>Please tell me about yourself</h1> <form action="SimpleFormHandler.jsp" method="get"> Name: <input type="text" name="firstName"> <input type="text" name="lastName"><br> Sex: <input type="radio" checked name="sex" value="male">Male <input type="radio" name="sex" value="female">Female <p> What Java primitive type best describes your personality: <select name="javaType"> <option value="boolean">boolean</option> <option value="byte">byte</option> <option value="char" selected>char</option> <option value="double">double</option> <option value="float">float</option> <option value="int">int</option> <option value="long">long</option> </select> <br> <input type="submit"> </form> </body> </html>
The SimpleFormHandler JSP does little more than retrieve the form variables and print out their values. Listing 3.2 shows the contents of SimpleFormHandler.jsp, which you can see is pretty short.
<html> <body> <% // Grab the variables from the form. String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String sex = request.getParameter("sex"); String javaType = request.getParameter("javaType"); %> <%-- Print out the variables. --%> <h1>Hello, <%=firstName%> <%=lastName%>!</h1> I see that you are <%=sex%>. You know, you remind me of a <%=javaType%> variable I once knew. </body> </html>
In Case of Trouble
Most of SimpleFormHandler.jsp should seem pretty familiar to you. It is very similar to an example in Hour 1, "Getting Started with JavaServer Pages," that used the <%= %> tags to assign some variables and print out their values. The only new thing introduced in Listing 3.2 is the built-in request object. Every JSP has a few built-in objects. The most common ones are out and request.
The out object was introduced in Hour 1 and is the output stream used to send data back to the browser. The request object contains information about the request from the browser, and although it contains quite a bit of information, the request object is most commonly used for retrieving the values of form variables.
The True Identity of request
As you look at the SimpleFormHandler JSP, it should be pretty obvious what the output would look like. Just to make sure you've got it, Figure 3.2 shows how SimpleFormHandler looks when displayed in a browser.
|[ Team LiB ]|