Way2Java

Read HTML Filelds getParameterValues() Example

getParameterValues(): 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(). These methods are inherited by HttpServletRequest interface.

First let us see what Servlet API says about these methods. These are defined in javax.servlet.ServletRequest interface.

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

getParameter(String) is used to read only one form field. getParameterNames() is used to read all form field data at a time.

When to use getParameterValues() to read form data?

Observe the following client HTML file, StudentAddress.html


  
Enter Name
Enter ID
Enter H.No.
Enter Street
Enter Area
Enter City
Enter PIN

Observe, there are total 7 form fields of which five fields are having a common name of t3. All the five form fields with t3 name comprises of a student address. The job of the servlet may be to extract all the 7 form fields data and enter into a database table. Imagine, the database have only 3 columns like stdname, stdid and stdaddress. The value of t1 goes into the stdname column, t2 goes into stdid and all the remaining five fields with name t3 goes into stdaddress.

How to do this job easily in a servlet?

Read t1 and t2 separately with getParameter(String) method as usual as you did in Login Screen Validation. Now comes our getParameterValues() method to read all the t3 values at a time. This method returns a string array containing all the values entered by the user in t3 fields. Take this array and enter into the database column. Ofcourse, the aim of this servlet is reading only but does not do any database operation.

web.xml entry for GetPNames servlet:


  efgh
  GetPNames



  efgh
  /readall

Servlet getParameterValues(): GetPNames.java

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

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

    String address[] = req.getParameterValues("t3");
 
    StringBuffer temp = new StringBuffer();
    for(String str : address)
    {
      temp.append(str + ", ");
    }        

    out.println(temp);
    out.close();
  }
}

getParameterValues(String) avoids reading separately. But the condition is all the fields should have the common name. The StringBuffer object temp can be taken and inserted into a database column.


Client-side HTML screen when values are entered.


Output screen on getParameterValues() Example when the submit button is clicked.