09 - Handling Form Data in Servlets

9.1 Overview

Handling client data or request is vital feature of any web application. We  all must have used this feature like Google search or filling a contact us page on any website etc. In this chapter we will learn how to handle client requests.

9.2  HTTP Request method types

There are several HTTP request method types available like GET,PUT,POST,DELETE, HEAD,OPTIONS etc.

  • GET- As it name suggests, it is to get a resource or data from server.
  • POST- Submit or post data to server for processing.
  • DELETE- To delete any resource from server.
  • HEAD- It is same as GET but in a response it just returns Header
  • PUT- To upload data on server.
  • OPTIONS- To know the methods supported by server.

Out of these HTTP Request method types, most commonly used methods are GET and POST so let’s discuss these methods in detail.

9.3  GET METHOD

Ideally this method should be used to get the data or resource from server but with GET method type we can send data to the server as well. There are several things which are important to understand about GET method.

  • As mentioned in above point , data is submitted in query param so it should never be used for sending sensitive information like passwords as data is clearly be seen in browser address bar.
  • GET requests have length restrictions which means there is a limit on the size of data that can be submitted to server.
  • Maximum length of URL can be 2048 characters.
  • GET is default method type.
  • GET request supports only ASCII characters as data .
  • GET request invokes doGet() method of HttpServlet

9.4  POST METHOD

This method is intended to submit the data to the server for processing. Some Important points about POST method type are –

  • Data submitted with POST method type is sent in message body so it is secure and cannot be seen in browser address bar.  
  • There is no limit on the data that can be sent through POST
  • POST request cannot be cached.
  • POST request supports binary data as well. We can upload file to the server using POST type.
  • POST request invokes doPost() method of HttpServlet.

9.5  Examples

9.5.1 Write a Login module to explain the difference between GET and POST

Solution- To submit a data from client , we need to have a HTML having a HTML form to display username and password field.

a. Add servlet entry in web.xml

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.servlet.tutorial.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>

b. Create a login.html file inside WebContent folder. Html file will contain one form with two input fields (username and password). In below html file , there is no method specified in form tag so it means request is GET as By default method type is GET.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Form</title>
</head>
<body>
<form name="logonform" action="LoginServlet" >
Username: <input type="text" name="username"/>
<br/>
Password:<input type="password" name="password"/>
<br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

c. Create LoginServlet which will read the request parameters using request.getParameter() method and display them.Login.html submits  username and password request parameter.

package com.servlet.tutorial;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet 
{
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String username=request.getParameter("username");
String password=request.getParameter("password");
PrintWriter writer = response.getWriter();
String message="Username is : "+ username + "<br/> Password is :" + password ;
writer.println(message);
}
}

 

Testing – Hit the http://localhost:8080/HelloWorld/login.html (refer below). It will display two field user name and password.

Enter the username and password and submit. I have used password field so you will not be

see the password.

Username and password is sent as a query param and can be clearly seen in browser address bar as well. This is what we discussed as a drawback of using GET type for form submission.

Let’s Change the program to submit it as POST.

a)Add method as POST in login.html (highlighted below)

<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<form name="logonform" action="LoginServlet" method="POST">
Username: <input type="text" name="username"/>
<br/>
Password:<input type="password" name="password"/>
<br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

b) Change the method to doPost() in LoginServlet

package com.servlet.tutorial;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet 
{
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String username=request.getParameter("username");
String password=request.getParameter("password");
PrintWriter writer = response.getWriter();
String message="Username is : "+ username + "<br/> Password is :" + password ;
writer.println(message);
}
}

Testing - Submit the form again and see the change. This time , data is sent as message body and not as query params.

 

9.5.2  

Write a servlet program to demonstrate the use of request.getParameterValues() API OR can say read multiple values of a same parameter.

Solution – To demonstrate request.getParameterValues() API, create html form with a group of check boxes. Since its a group, all of the check boxes will have same name but multiple values will be submitted.

a. Add entry in servlet.xml

<servlet>
    <servlet-name>ReadMultipleValuesServlet</servlet-name>
<servlet-class>
com.servlet.tutorial.ReadMultipleValuesServlet
</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ReadMultipleValuesServlet</servlet-name>
        <url-pattern>/ReadMultipleValuesServlet</url-pattern>
</servlet-mapping>

b. Create checkbox.html which contains a group of three check box

<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<H1>Which all fruits do you like ? </H1>
<form name="Mutliple Values" action="ReadMultipleValuesServlet" method="POST">
Orange <input type ="checkbox" name="CheckBoxGrp" value="Orange"/>
<br/>
Apple <input type ="checkbox" name="CheckBoxGrp" value="Apple"/>
<br/>
Banana<input type ="checkbox" name="CheckBoxGrp" value="Banana"/>
<br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

c. Write ReadMultipleValuesServlet. As the checkbox is group and multiple values can be selected by user so read the request using request.getParameterValues() method which will return array of all selected check box .

package com.servlet.tutorial;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ReadMultipleValuesServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        String message="";
        String values[] = request.getParameterValues("CheckBoxGrp");
        if(values!=null)
        {
            for(int i=0;i<values.length;i++)
        {
            message= message+ "<BR/>" + values[i];
        }
    }
    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();
    writer.println(message);
    }
}

Testing – Hit the url http://localhost:8080/HelloWorld/checkbox.html

Select the fruits of your choice and submit the form by clicking Submit button.

 

  1. – We don’t know the name of  form elements OR we can say request parameters. Write a program which will display all the submitted values.

Solution – Since we don’t know the name of request parameters , we cannot use request.getParameter(paramName) because this API needs the parameter name which we don’t know.

API also provides a method request.getParameterNames() which returns the Enumeration of all parameters name submitted.

We can simply use this API to get the name of all parameters and then call request.getParameter() for each parameter.

a. Add entry in web.xml

<servlet>
    <servlet-name>ReadAllRequestParametersServlet</servlet-name>
<servlet-class>
com.servlet.tutorial.ReadAllRequestParametersServlet
</servlet-class>
</servlet>
<servlet-mapping>
        <servlet-name>ReadAllRequestParametersServlet</servlet-name>
        <url-pattern>/ReadAllRequestParametersServlet</url-pattern>
    </servlet-mapping>

b. Create ContactForm.html with three input fields (name ,address,contact number )

<!DOCTYPE html>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
    <form name="contactform" action="ReadAllRequestParametersServlet"
        method="POST">
        Name: <input type="text" name="name" /> <br /> 
Address:<input type="text" name="address" /> <br /> 
Contact Number:<input type="text" name="contact" /> <br /> 
<input type="submit"value="Submit" />
    </form>
</body>
</html>

c. Write a ReadAllRequestParametersServlet servlet. In this code we have not hard coded any request parameter name.

package com.servlet.tutorial;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ReadAllRequestParametersServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        Enumeration<String> paramEnumeration= request.getParameterNames();
        StringBuffer buffer = new StringBuffer();
        while(paramEnumeration.hasMoreElements())
        {
            String paramName= paramEnumeration.nextElement();
            String paramValue =request.getParameter(paramName);
            buffer.append(paramName + ":" + paramValue);
            buffer.append("<br/>");
        }
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.println(buffer.toString());
    }
}

Testing

Hit the url http://localhost:8080/HelloWorld/ContactForm.html

Enter the details and submit

 

9.5.4  

What will happen if servlet implements only doPost() and request is invoked with GET or a vice versa?

Solution – If servlet has implemented only doPost() and we make a GET request for that servlet, than we will get an error saying “HTTP method GET is not supported by this URL” or if doGet() is implemented and request came for POST, we will see “HTTP method POST is not supported by this URL

To validate this , just invoke any of the servlet which has implemented only doPost() .Lets take any one from above examples. ReadAllRequestParameterServlet  has just doPost() so hitting http://localhost:8080/HelloWorld/ReadAllRequestParametersServlet will display below page

TIP- If you want to have same functionality in both doGet() and doPost() method then do not duplicate the code in both method. Instead, write a common method and call that method from both like below.

private void commonCode(HttpServletRequest request,HttpServletResponse)
{
// common code 
} 
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
{
    commonCode(request,response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
{
    commonCode(request,response);
}

 

Like us on Facebook