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.

  • public java.lang.String getParameter(java.lang.String name): Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.
  • public java.util.Enumeration getParameterNames():
    Returns an Enumeration of String objects containing the names of the parameters contained in this request. If the request has no parameters, the method returns an empty Enumeration.
  • public java.lang.String[] getParameterValues(java.lang.String name):
    Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. If the parameter has a single value, the array has a length of 1.

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:

getParameterNames()

Output screen when submit button clicked:

getParameterNames()

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

6 thoughts on “getParameterNames() Example Servlets”

  1. Mohammed Rafeeq

    Thank you
    Your blog helped me a lot !!
    Do I need to create different servlet code for each query for example Im making a database of pilots and aircrafts and when I click a button of pilot a servlet code must give the details of pilots and when I click aircraft button do I need to write a different servlet code to retrieve details of aircraft or can I do it in same servlet code

  2. sandeep kumar rai

    /* Sir, can you please tell me the problem.. while executing the exception block is getting executed ..*/

    public class myservlet extends HttpServlet {

    /**
    * Processes requests for both HTTP GET and POST methods.
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
    protected void signup(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, NamingException ,SQLException{
    response.setContentType(“text/html;charset=UTF-8″);
    PrintWriter out = response.getWriter();
    try
    {
    String [] values = new String [10];
    Context cx=new InitialContext();
    DataSource ds=(DataSource) cx.lookup(“jdbc/myDatasource”);
    Connection conn=ds.getConnection();
    Enumeration en=request.getParameterNames();
    String str=”insert into sign values(?,?,?)”;
    PreparedStatement pos=conn.prepareStatement(“str”);
    for(int i=0;en.hasMoreElements();i++)
    {
    String param=(String) en.nextElement();

    values [i]=request.getParameter(“param”);

    pos.setString(i,values[i]);
    }

    // String str=”insert into sign values(?,?,?)”;

    // PreparedStatement pos=conn.prepareStatement(“str”);
    // for(int i=1;en.hasMoreElements();i++)
    // {
    // pos.setString(i,values[i]);
    // }

    RequestDispatcher dss=request.getRequestDispatcher(“index.jsp”);
    dss.forward(request, response);
    }catch(Exception e)
    {

    RequestDispatcher dss=request.getRequestDispatcher(“error.jsp”);

    dss.forward(request, response);

    }
    try {
    /* TODO output your page here
    out.println(“”);
    out.println(“”);
    out.println(“Servlet myservlet”);
    out.println(“”);
    out.println(“”);
    out.println(“Servlet myservlet at ” + request.getContextPath () + “”);
    out.println(“”);
    out.println(“”);
    */
    } finally {
    out.close();
    }
    }
    – See more at: http://way2java.com/servlets/servlets-getparametervalues-example/comment-page-1/#comment-32753

      1. sandeep kumar rai

        /* Sir ,i got the output .. a little change was there in the code . */

        /*
        * To change this template, choose Tools | Templates
        * and open the template in the editor.
        */

        import java.io.IOException;
        import java.io.PrintWriter;
        import java.lang.String;
        import java.sql.Connection;
        import java.sql.PreparedStatement;
        import java.sql.SQLException;
        import java.util.Enumeration;
        import java.util.logging.Level;
        import java.util.logging.Logger;

        import javax.naming.Context;
        import javax.naming.InitialContext;
        import javax.naming.NamingException;
        import javax.servlet.RequestDispatcher;

        import javax.servlet.ServletException;
        import javax.servlet.http.HttpServlet;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import javax.sql.DataSource;
        import org.hibernate.validator.util.SetAccessibility;

        /**
        *
        * @author Administrator
        */
        public class myservlet extends HttpServlet {

        /**
        * Processes requests for both HTTP GET and POST methods.
        * @param request servlet request
        * @param response servlet response
        * @throws ServletException if a servlet-specific error occurs
        * @throws IOException if an I/O error occurs
        */
        protected void signup(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, NamingException ,SQLException{
        response.setContentType(“text/html;charset=UTF-8”);
        PrintWriter out = response.getWriter();
        try
        {
        String [] values = new String [100];
        Context cx=new InitialContext();
        DataSource ds=(DataSource) cx.lookup(“jdbc/myDatasource”);
        Connection conn=ds.getConnection();
        String str=”insert into sign values(?,?,?)”;
        PreparedStatement pos=conn.prepareStatement(str);
        Enumeration en=request.getParameterNames();

        for(int i=1;en.hasMoreElements();i++)
        {

        String param=(String) en.nextElement();

        values [i]=request.getParameter(param); // by mistake i used values [i]=request.getParameter(“param”);

        pos.setString(i,values[i]);

        }
        pos.executeUpdate();

        /* int i=0;
        String str=”insert into sign values(?,?,?)”;
        StringBuffer temp= new StringBuffer();
        PreparedStatement pos=conn.prepareStatement(“str”);

        for(String strr : values)
        {
        pos.setString(i, strr);
        i++;
        }*/
        // String str=”insert into sign values(?,?,?)”;

        // PreparedStatement pos=conn.prepareStatement(“str”);
        // for(int i=1;en.hasMoreElements();i++)
        // {
        // pos.setString(i,values[i]);
        // }

        RequestDispatcher dss=request.getRequestDispatcher(“index.jsp”);
        dss.forward(request, response);
        }catch(Exception e)
        {
        e.printStackTrace();
        RequestDispatcher dss=request.getRequestDispatcher(“error.jsp”);

        dss.forward(request, response);

        }
        try {
        /* TODO output your page here
        out.println(“”);
        out.println(“”);
        out.println(“Servlet myservlet”);
        out.println(“”);
        out.println(“”);
        out.println(“Servlet myservlet at ” + request.getContextPath () + “”);
        out.println(“”);
        out.println(“”);
        */
        } finally {
        out.close();
        }
        }

        //
        /**
        * Handles the HTTP GET method.
        * @param request servlet request
        * @param response servlet response
        * @throws ServletException if a servlet-specific error occurs
        * @throws IOException if an I/O error occurs
        */
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        try {
        try {
        signup(request, response);
        } catch (SQLException ex) {
        Logger.getLogger(myservlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        } catch (NamingException ex) {
        Logger.getLogger(myservlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        }

        /**
        * Handles the HTTP POST method.
        * @param request servlet request
        * @param response servlet response
        * @throws ServletException if a servlet-specific error occurs
        * @throws IOException if an I/O error occurs
        */
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        try {
        try {
        signup(request, response);
        } catch (SQLException ex) {
        Logger.getLogger(myservlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        } catch (NamingException ex) {
        Logger.getLogger(myservlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        }

        /**
        * Returns a short description of the servlet.
        * @return a String containing servlet description
        */
        @Override
        public String getServletInfo() {
        return “Short description”;
        }//

        }

Leave a Comment

Your email address will not be published.