Servlet - Handling Form Data


With servlets we can read data that has beeen submited from a html form. HttpServletRequest allows us to read the form data.

In the following examples, we explain how to read the form data.

Step 1: Create the form which geneartes the Fields

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Form Reading using Servlet</title>
</head>
<body>
	<form action="getFormDetails">
		Username:&nbsp;<input type="text" name="username" value="" /><br/>
		Password:&nbsp;&nbsp;<input	type="password" name="password" value="" /> <br/>
		Gender: &nbsp;&nbsp; 
			<input type="radio" value="male" name="gender">Male 
			<input type="radio" value="feMale" name="gender">FeMale<br/>
		   <input type="submit"
			value="ShowFormDetails">
	</form>
</body>
</html>

Step 2: Create a servlet that reads submited data and renders a new page

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 FormReadServelt extends HttpServlet {
	

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		// read the from data using the httpservletrequest
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String gender = req.getParameter("gender");
		
		// show the data on page
		PrintWriter out = resp.getWriter();
		out.println("<html>"); 
		out.println("<body>");
		out.println("<h3>Name: " + username +"</h3>");
		out.println("<h3>Password: " + password +"</h3>");
		out.println("<h3>Gender: " + gender +"</h3>");
		out.println("</body>");
		out.println("</html>");
	}

}

Step 3: Configure the servlet and mapping in web.xml

<?xml version="1.0" encoding="ISO-8859-1" ?>

<web-app>
	version="2.4">
	
	<welcome-file-list>
		<welcome-file>simpleform.html</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>FormData</servlet-name>
		<servlet-class>FormReadServelt</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>FormData</servlet-name>
		<url-pattern>/getFormDetails</url-pattern>
	</servlet-mapping>

</web-app>

After following steps 1-3, run the application on the server. You should be able to see the page which allows you to enter the form details. The details that you would enter will be displayed on next page after clicking the GetFormDetails button.