Tuesday, 8 April 2014

Servlets : Form Data Example - GET Method

🚀 Master Java Servlets & Web Development!

Subscribe to Ram N Java for clean, beginner-friendly coding tutorials and practical web architecture guides!

👉 Click Here to Subscribe Now

Understanding the HTTP GET Method in Form Handling

The GET method is the default and most commonly used HTTP request method for retrieving data from a web server. When an HTML form is submitted using method="get", the browser encodes form input fields as key-value pairs and appends them directly to the target URL as a query string (e.g., GetServlet?firstName=John&lastName=Doe).

In Java Servlets, requests sent using the GET method trigger the servlet container to call the doGet() method of your HttpServlet subclass.

Step 1: Create the HTML GET Form (index.html)

Design an HTML form specifying method="get" and the mapping path of your servlet in the action attribute:

<form action="GetMethodServlet" method="get">
  First Name: <input type="text" name="firstName" /><br><br>
  Last Name: <input type="text" name="lastName" /><br><br>
  <input type="submit" value="Submit via GET" />
</form>

Step 2: Read GET Parameters in the Servlet (GetMethodServlet.java)

Inside your servlet, override the doGet() method and retrieve the submitted query string values using request.getParameter():

@WebServlet("/GetMethodServlet")
public class GetMethodServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");

    out.println("<h2>Form Submitted Successfully via GET!</h2>");
    out.println("<p>First Name: <strong>" + firstName + "</strong></p>");
    out.println("<p>Last Name: <strong>" + lastName + "</strong></p>");
  }
}

Key Characteristics of the GET Method

  • Bookmarkable & Shareable: Because parameter values are appended to the URL query string, users can bookmark, refresh, or share the complete URL with search queries or filters.
  • Not for Sensitive Data: Passwords, payment details, or personal data should never use the GET method, as values are visible in the address bar, browser history, and web server access logs.
  • Size Limitations: Most web browsers and HTTP servers enforce limits on URL length (typically between 2,048 to 8,192 characters).
  • Idempotent & Safe: GET requests should typically retrieve data without modifying state or causing permanent server-side side effects.

📺 Related Form Processing Tutorials

Continue exploring form processing and parameter retrieval with these tutorials from our channel:


Click here to watch in Youtube : https://www.youtube.com/watch?v=m6rge4XteiI

Click the below Image to Enlarge

ServletFormDataGET Project Dir Structure


CustomerInfoServlet.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CustomerInfoServlet extends HttpServlet
{

 private static final long serialVersionUID = 1L;

 public void init()
 {
  System.out.println("-----------------------------------------------------");
  System.out.println("init method has been called and servlet is initialized");
  System.out.println("-----------------------------------------------------");
 }

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 {

  response.setContentType("text/html");

  PrintWriter out = response.getWriter();

  out.println("Read data using  '<b>String getParameter(String name)</b>' method");

  String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
  out.println(docType + "<html>\n" + "<head><title>" + "GET" + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<ul>\n" + "  <li><b>First Name</b>: " + request.getParameter("first_name")
          + "\n" + "  <li><b>Last Name</b>: " + request.getParameter("last_name") + "\n" + "</ul>\n" + "</body></html>");

  out.println("\nRead data using '<b>Enumeration getParameterNames()</b>' method \n");

  Enumeration<String> paramNames = request.getParameterNames();

  out.println("<ul>");

  while (paramNames.hasMoreElements())
  {

   String paramName = paramNames.nextElement();
   out.print(" <li><b>" + paramName + ":</b>");
   String paramValue = request.getParameter(paramName);
   out.println(paramValue + "</li>");

  }

  out.println("</ul>");

  out.println("\nRead data using '<b>Map getParameterMap()</b>' method\n");

  Map<String, String[]> paramMap = request.getParameterMap();

  Set<String> paramNamesSet = paramMap.keySet();

  out.println("<ul>");
  for (String paramName : paramNamesSet)
  {
   out.print(" <li><b>" + paramName + ":</b>");
   String[] paramValue = paramMap.get(paramName);
   for (int i = 0; i < paramValue.length; i++)
   {
    out.println(paramValue[i] + "</li>");
   }

  }
  out.println("</ul>");

 }

 public void destroy()
 {
  System.out.println("-----------------------------------------------------");
  System.out.println("destroy method has been called and servlet is destroyed");
  System.out.println("-----------------------------------------------------");
 }
}

web.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true" version="3.0">
  <display-name>ServletForm GET</display-name>
  <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>
  <servlet>
    <servlet-name>CustomerInfoForm</servlet-name>
    <servlet-class>CustomerInfoServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CustomerInfoForm</servlet-name>
    <url-pattern>/CustomerInfoForm</url-pattern>
  </servlet-mapping>
</web-app>

index.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<!DOCTYPE HTML><html lang="en"><head>
<meta charset="UTF-8">
<title>ServletForm GET</title>
</head>
<body>
<p>
<h3>ServletForm GET</H3>
<p></p>
<ul>
 <li><a href="customerform.html">Customer Form</a></li>
</ul>
</body></html>

customerform.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<html>
<body>
 <form action="CustomerInfoForm" method="GET">
 
 First Name: <input type="text" name="first_name">
 <br />
 
 Last Name: <input type="text" name="last_name" />
 
 <input type="submit" value="Submit" />
 
 </form>
</body>
</html>

Environment Used 

JDK version :1.6.0_30
Tomcat version : 7.0.50 

To Download ServletFormDataGETApp Project Click the below link

https://sites.google.com/site/javaee4321/servlets/ServletFormDataGETApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • 2 comments:

    1. Sir,
      Awesome work...
      It is very good to see someone doing such a great job !! I was very confused with working of the forms n the servlet ! Nicely explained !!
      Cheer!! Keep it Up !!
      PS: Please develop a site on a custom domain n hosting it would be great to see your sites and efforts to reach large audience all over the world!!

      ReplyDelete

    Tutorials