advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorials : Server-Side Web Applications Using Servlets and JSP :
Handling Form Data :

Contents
Introduction
Reading Three Parameters
Listing All Form Data

Example: Listing All Form Data

Here's an example that looks up all the parameter names that were sent and puts them in a table. It highlights parameters that have zero values as well as ones that have multiple values. First, it looks up all the parameter names via the "getParameterNames" method of "HttpServletRequest". This returns an "Enumeration". Next, it loops down the "Enumeration" in the standard manner, using "hasMoreElements" to determine when to stop and using "nextElement" to get each entry. Since "nextElement" returns an "Object", it casts the result to a "String" and passes that to "getParameterValues", yielding an array of "Strings". If that array is one entry long and contains only an empty string, then the parameter had no values, and the servlet generates an italicized "No Value" entry. If the array is more than one entry long, then the parameter had multiple values, and they are displayed in a bulleted list. Otherwise the one main value is just placed into the table.

You can also download the source or try it on-line. Note: also uses ServletUtilities.java, shown earlier.

package hall;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

/** Shows all the parameters sent to the servlet via either
 *  GET or POST. Specially marks parameters that have no values or
 *  multiple values.
 *

 *  Part of tutorial on servlets and JSP that appears at
 *  http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/
 *  1999 Marty Hall; may be freely used or adapted.
 */

public class ShowParameters extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Reading All Request Parameters";
    out.println(ServletUtilities.headWithTitle(title) +
                "<BODY BGCOLOR=\"#FDF5E6\">\n" +
                "<H1 ALIGN=CENTER>" + title + "</H1>\n" +
                "<TABLE BORDER=1 ALIGN=CENTER>\n" +
                "<TR BGCOLOR=\"#FFAD00\">\n" +
                "<TH>Parameter Name<TH>Parameter Value(s)");
  Enumeration paramNames = request.getParameterNames();
  while(paramNames.hasMoreElements()) {
    String paramName = (String)paramNames.nextElement();
    out.println("<TR><TD>" + paramName + "\n<TD>");
    String[] paramValues = request.getParameterValues(paramName);
    if (paramValues.length == 1) {
  	  String paramValue = paramValues[0];
	  if (paramValue.length() == 0)
	    out.print("<I>No Value");
	  else
	    out.print(paramValue);
    } else {
	  out.println("<UL>");
	  for(int i=0; i<paramValues.length; i++) {
	    out.println("<LI>" + paramValues[i]);
	  }
	  out.println("</UL>");
    }
  }
  out.println("</TABLE>\n</BODY></HTML>");
}				  }


  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}

Front End to ShowParameters

Here's an HTML form that sends a number of parameters to this servlet. Right click on the source code link to download the HTML. Left click on the link to try it out on-line. It uses POST to send the data (as should all forms that have PASSWORD entries), demonstrating the value of having servlets include both a "doGet" and a "doPost". However, just for the sake of illustration, a version using GET can also be downloaded or tried out on-line.

PostForm.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
  <TITLE>A Sample FORM using POST</TITLE>
</HEAD>

<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">A Sample FORM using POST</H1>
<FORM ACTION="/servlet/hall.ShowParameters"
      METHOD="POST">
  Item Number:
  <INPUT TYPE="TEXT" NAME="itemNum"><BR>
  Quantity:
  <INPUT TYPE="TEXT" NAME="quantity"><BR>
  Price Each:
  <INPUT TYPE="TEXT" NAME="price" VALUE="$"><BR>
  <HR>
  First Name:
  <INPUT TYPE="TEXT" NAME="firstName"><BR>
  Last Name:
  <INPUT TYPE="TEXT" NAME="lastName"><BR>
  Middle Initial:
  <INPUT TYPE="TEXT" NAME="initial"><BR>
  Shipping Address:
  <TEXTAREA NAME="address" ROWS=3 COLS=40></TEXTAREA><BR>
  Credit Card:<BR>
    <INPUT TYPE="RADIO" NAME="cardType"
                     VALUE="Visa">Visa<BR>
    <INPUT TYPE="RADIO" NAME="cardType"
                     VALUE="Master Card">Master Card<BR>
    <INPUT TYPE="RADIO" NAME="cardType"
                     VALUE="Amex">American Express<BR>
    <INPUT TYPE="RADIO" NAME="cardType"
                     VALUE="Discover">Discover<BR>
    <INPUT TYPE="RADIO" NAME="cardType"
                     VALUE="Java SmartCard">Java SmartCard<BR>
  Credit Card Number:
  <INPUT TYPE="PASSWORD" NAME="cardNum"><BR>
  Repeat Credit Card Number:
  <INPUT TYPE="PASSWORD" NAME="cardNum"><BR><BR>
  <CENTER>
    <INPUT TYPE="SUBMIT" VALUE="Submit Order">
  </CENTER>
</FORM>

</BODY>
</HTML>

Submission Result


This tutorial is now available as a book: Core Servlets and JavaServer Pages by Marty Hall, published by Sun Microsystems Press. Read all about it at CoreServlets.com


Server-Side Web Applications using Java Servlets versions 2.1/2.2 and JavaServer Pages (JSP) version 1.0: A Tutorial
© 1999-2000 Marty Hall.
All source code freely available for unrestricted use.
Created for work in the Research and Technology Development Center of the Johns Hopkins University Applied Physics Lab, for courses in the Johns Hopkins Part-Time MS Program in Computer Science, and for various industry seminars and on-site Java short courses.
Please note that this is a first draft of the tutorial, so please send corrections, comments, and suggestions to me at hall@apl.jhu.edu.
Reprinted with permission from the author. Click here to visit the original version

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

XML error: undefined entity at line 19
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Linux Vendors Head to the Cloud in Search of Cash
iPhone 3GS: Overheating Fears, OS Update Nears
PostgreSQL 8.4 Revs Up Database Admin, Security
PHP 5.3 Accelerates PHP
Sun Releases NetBeans 6.7 IDE for Java, PHP
Why Firefox Doesn't Take Google Chrome Features
First Major PHP Update in Years Coming Soon
Red Hat CEO Calls on Oracle to Keep Java Open
Google Widens AdSense for iPhone, Android Apps
Eclipse Galileo Releases 33 Open Source Projects

A Taste of JavaFX for the Uninitiated
A Guide to Caching and Compression for High Performance Web Applications
How User-Centered Design Can Put User Stories in Proper Context
Explore C# 4's New Dynamic Types and Named/Optional Parameters
Enterprise Architecture: The Journey Begins Here, Part 2
Create a Syslog Sender/Receiver Using the MS Winsock Control
AMD CodeAnalyst Helps Developers Optimize and Tune Applications
Securing Microsoft's Cloud Infrastructure
Introducing the Azure Services Platform
An Introduction to Microsoft .NET Services for Developers

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs