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>
<meta charset="ISO-8859-1">
<title>Form Reading using Servlet</title>
	<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"

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


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("<h3>Name: " + username +"</h3>");
		out.println("<h3>Password: " + password +"</h3>");
		out.println("<h3>Gender: " + gender +"</h3>");


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

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




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.