Read HTML Form Data in 3 Styles with Servlets

One of the activities of a Servlet Developer is to read HTML form data sent by the client by clicking over Submit button. The data sent by the client lands finally in ServletRequest/HttpServletRequest object passed as parameter to service() method. To retrieve the data from ServletRequest object, the ServletRequest interface comes with three methods mostly used.
They are getParameter(String), getParameterNames() and getParameterValues(String).

Let us see what Java API says about these methods as defined in javax.servlet.ServletRequest interface and inherited by HttpServletRequest 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.
  1. getParameter(String) is used to read only one form field data as a string. Example is available at Login Screen Validation.
  2. getParameterNames() is used to read all form fields data at a time as an Enumeration object. Example is available at Servlet getParameterNames() Example.
  3. getParameterValues(String) is used to read multiple form field data as a string array where fields have some common name. Example is available at Servlets getParameterValues() Example.
To Read HTML Form Data, examples are given in the above list in Simple terms, Screenshots and Diagrams.

Leave a Comment

Your email address will not be published.