CS6320:  SW Engineering of Web Based Systems

 

   Servlet:  Reading in HTML Form Data
  • A common use of an HTTP Servlet is to process HTML form data.
  • HTML Form data is sent via a GET or POST Method, and is in name/value pairs refered to as parameters.



How to read in HTML form data in a Servlet:
 
do the same thing regardless of wether a GET or POST submission
1) Inside of the doGet and/or doPost methods of your servlet invoke the getParameter or getParameterValues methods of the HTTPServletRequest instance.
  • getParameter("name")  = returns a String representing value of parameter "name".
    •  
      String value = getParameter("name");
      //now process this value
       
  • getParameterValues("name") = returns an instance of the Enumeration class, that contains a series of entries that can be cast to Strings. 
    •  

      Enumeration e = getParameters("name");
      while(e.hasMoreElements()) {

        String value = (String) e.nextElement();
        //now process this value 
      }
         


2) Process values as desired.

If desired you can read the Raw, unparsed, non URL-decoded form (query) data.
 
  • Recall, HTML forms send data using CGI standard (review if necessary), that contain special characters like ?, & and % that have special meaning and with other languages you must parse this input.  In Java we are lucky to have the getParameter() and getParameterValues() methods.  But, sometimes you may want to have access to this raw data.
  • Here is an example:
    • http://f.com/ProcessServlet?param1=value1&param2=value2
  • HOW TO GET THIS DATA:
    • 1) Create a Reader or InputStream associated with the HttpServletRequest parameter of your doGet and/or doPost methods:
         
        Reader r = request.getReader();
      2) Now use Reader or InputStream to read in the data.  You must parse and decode the data as you did before with other languages parsing CGI data.
     
Exercise
© Lynne Grewe