Open In App

Servlet – Form Data

Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver. Properties of Servlets are as follows:

So, what do you mean by ‘handling the client data‘?

We must have come across many situations where we need to fill a form with our data to access some application. In this situation, as a developer, you need to handle that data or information to pass from the browser to the web/application server and finally to your backend program to process that request. In this chapter, we will learn how to handle this form of data using Servlets.



HttpServlet Class

Java provides HttpServlet class which extends the GenericServlet class to process HTTP-specific request/response for a website.  It provides HTTP specific methods such as doGet(), doPost(), doPut(), doDelete() etc. If we are extending the HttpServlet in our class, we must override at least one of these methods to process the request and send the response. We need to use either doGet() or doPost() method in the servlet class to get the information from the browser based on the method specified in the form. 

GET method type and doGet() method

The doGet() method in servlets is used to process the HTTP GET requests. So, basically, the HTTP GET method should be used to get the data from the server to the browser. Although in some requests, the GET method is used to send data from the browser to the server also. In this case, you need to understand the below points on how the GET method will work.



POST method type and doPost() method

The doPost() method in servlets is used to process the HTTP POST requests. It is used to submit the data from the browser to the server for processing. The data submitted with POST method type is sent in the message body so it is secure and cannot be seen in the URL.  And there is no limit on the data that can be sent through the POST method. Ideally, we need to use the POST method, to send the form data to the webserver. So, we will be using the doPost() method in this example. And we will learn how to handle some of the common HTML fields data such as Text field, Checkbox, Radio button, Dropdown, etc., values in the servlet.

To achieve this, Java provides ServletRequest interface. 

HttpServletRequest(I):

getParameter() method:

Syntax:




// String type specifying the parameter 
// name of which the value to be returned as String
java.lang.String getParameter(java.lang.String name)

getParameterValues() method:

The method returns an array of String objects containing all of the values of the given field/parameter from the request. If the specified parameter name does not exist, it returns null.

Syntax:




// String type specifying the parameter name
// of which the values to be returned in array
java.lang.String[] getParameterValues(java.lang.String name)

Example

We will create a simple form to get the details from client like below,

Application Form

 

Steps to create the application:

Create Details.html page:




<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Details</title>
</head>
<body >
    <h3>Fill in the Form</h3>
  
    <form action="FormData" method="post">
        <table>
  
            <tr>
                <td>Full Name:</td>
                <td><input type="text" name="name" /></td>
            </tr>
            <tr>
                <td>Phone Number:</td>
                <td><input type="text" name="phone" /></td>
            </tr>
            <tr>
                <td>Gender:</td>
                <td><input type="radio" name="gender" value="male" />Male 
                    <input type="radio" name="gender" value="female" />Female</td>
            </tr>
            <tr>
                <td>Select Programming Languages to learn:</td>
                <td><input type="checkbox" name="language" value="java" />Java
                    <input type="checkbox" name="language" value="python" />Python
                    <input type="checkbox" name="language" value="sql" />SQL
                    <input type="checkbox" name="language" value="php" />PHP</td>
            </tr>
            <tr>
                <td>Select Course duration:</td>
                <td><select name="duration">
                    <option value="3months">3 Months</option>
                    <option value="6months">6 Months</option>
                    <option value="9months">9 Months</option></select></td>
            </tr>
            <tr>
                <td>Anything else you want to share:</td>
                <td><textarea rows="5" cols="40" name="comment"></textarea></td>
            </tr>
  
        </table>
  
        <input type="submit" value="Submit Details">
  
    </form>
  
</body>
</html>

Create FormDataHandle.java Servlet:




import java.io.IOException;
import java.io.PrintWriter;
  
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
// Servlet implementation class FormDataHandle
  
// Annotation to map the Servlet URL
@WebServlet("/FormData")
public class FormDataHandle extends HttpServlet {
    private static final long serialVersionUID = 1L;
  
    // Auto-generated constructor stub
    public FormDataHandle() {
        super();
    }
  
    // HttpServlet doPost(HttpServletRequest request, HttpServletResponse response) method
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
        // Get the values from the request using 'getParameter'
        String name = request.getParameter("name");
        String phNum = request.getParameter("phone");
        String gender = request.getParameter("gender");
          
        // To get all the values selected for 
        // programming language, use 'getParameterValues'
        String progLang[] = request.getParameterValues("language");
        
        // Iterate through the String array to 
        // store the selected values in form of String
        String langSelect = "";
        if(progLang!=null){
            for(int i=0;i<progLang.length;i++){
                langSelect= langSelect + progLang[i]+ ", ";
            }
        }
          
        String courseDur = request.getParameter("duration");
        String comment = request.getParameter("comment");
                  
        // set the content type of response to 'text/html'
        response.setContentType("text/html");
          
        // Get the PrintWriter object to write 
        // the response to the text-output stream
        PrintWriter out = response.getWriter();
          
        // Print the data
        out.print("<html><body>");
        out.print("<h3>Details Entered</h3><br/>");
          
        out.print("Full Name: "+ name + "<br/>");
        out.print("Phone Number: "+ phNum +"<br/>");
        out.print("Gender: "+ gender +"<br/>");
        out.print("Programming languages selected: "+ langSelect +"<br/>");
        out.print("Duration of course: "+ courseDur+"<br/>");
        out.print("Comments: "+ comment);
          
        out.print("</body></html>");
          
    }
  
}

Explanation:

As we learned, to get the field value having only one value, ‘getParameter()‘ is used. So for the fields,

getParameter()‘ returns the respective parameter value as a String. But the ‘Programming Languages’ field is the type Checkbox, we can have multiple values selected for this checkbox. So ‘getParameterValues()‘ method returns all the selected values as an array. This way all the input data entered in the browser will pass through the request body to the respective servlets. After getting the parameter values, we can perform our own logic to process the information such as,

In this example, we are simply writing the input data we got from the request object to the browser through the response object. To achieve this, we are using the PrintWriter class object from java.io package.

Output:

Details.html page

Output details

This way, we can handle the HTML form data in the Servlet classes using methods in HttpServletRequest Interface.


Article Tags :