Way2Java

getParameterNames() Example Servlets

One of the aspects of Servlets is reading the HTML/Applet data sent by the client like login data etc. For this, three methods exist in ServletRequest interface – getParameter(String), getParameterNames() and getParameterValues(String). These methods are inherited by HttpServletRequest interface.

Following are the method signatures as defined in javax.servlet.ServletRequest interface.

The first method getParameter(String) is explained in Login Screen Validation and the third in Servlets getParameterValues() Example. Now let us see the second one, getParameterNames().

getParameter(String) is used to read only one form field. getParameterNames() is used to read all form field data at a time. Let us explain further with an example.

Client Program: StudentAddress.html


  
Enter Student Name
Enter Student ID
Enter Student Marks
Enter Student Branch
Enter Student College
Enter Student Residence

Observe, there are 6 form fields from t1 to t6. The aim of this servlet is to read all at a time.

web.xml entry for GetPNames servlet:


  efgh
  GetPNames



  efgh
  /readall

Servlet: GetPNames.java

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

public class GetPNames extends HttpServlet
{
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    Enumeration e = req.getParameterNames();
 
    while(e.hasMoreElements())
    {
      Object obj = e.nextElement();
      String fieldName = (String) obj;
      String fieldValue = req.getParameter(fieldName);
      out.println(fieldName + " : " + fieldValue + "
"); } out.close(); } }

Enumeration e = req.getParameterNames();

The getParameterNames() of ServletRequest (inherited by HttpServletRequest) returns an object of java.util.Enumeration.

Object obj = e.nextElement();
String fieldName = (String) obj;
String fieldValue = req.getParameter(fieldName);

The e object of Enumeration contains all the names of fields like t1, t2, t3 etc. but not their values entered by the user. The nextElement() returns one field name for each iteration. The field name is passed to getParameter(fieldName) method to retrieve the value entered by the user.

HTML file when all the fields are filled up:

Output screen when submit button clicked:

Note: Observe, the output is not in correct order (infact, it is in reverse order). It is the problem with Enumeration; anyhow, here order is not important.

View all Servlets