How to retrieve a form at Server end using Servlet

Purpose:

    How to retrieve data from various fields of a particular form at Server Side, specially when multiple field names are same

Steps:

1) Create “MyServlet.java”, as servlet file (don’t know how to create a servlet file in Eclipse? Refer to our post: “ Servlet in Eclipse IDE“)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet
{
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		response.setContentType("text/html"); // informing the client that which format of data/response will be send
		PrintWriter out= response.getWriter(); 
		
		String Values[] = request.getParameterValues("num"); 
		// will retrieve all field values entered by user using "getParameterValues()"
		// and store in STRING ARRAY
		
		out.println("<h3> The Values are </br>");
		
		for(int i=0; i<Values.length; i++)
		{
			out.println("<br>" +Values[i]); // print all field values entered by user in form
		}
	}

}

2) Create “index.html”, as HTML file (you can refer: “How to add HTML file in your Servlet Program using Eclipse“)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="MyServlet" method="get">
<input type="text" name="num"><br>  //Field 1 name is "num"
<input type="text" name="num"><br> //Field 2 name is "num"
<input type="text" name="num"><br> 
//Field 3 name is "num". 
//So all 3fields name are same, 
//Let's check whether we be able to retrieve & differentiate data entered by user in these fields.

<input type="Submit" value="Submit">

</form>
</body>
</html>

3) Press “CTRL+F11”

4) Output will be

Enter values in field and click on “Submit” button

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s