Servlets - Form Data


You probably go over numerous circumstances when you have to pass some data from your program to web server and at last to your backend program. The program utilizes two strategies to pass this data to web server. These strategies are GET Method and POST Method.

GET Method

The GET strategy sends the encoded client data annexed to the page ask. The page and the encoded data are isolated by the ? (question mark) image as pursues −

http://www.test.com/hello?key1 = value1&key2 = value2 

The GET strategy is the default technique to pass data from program to web server and it creates a long string that shows up in your program's Location:box. Never utilize the GET strategy on the off chance that you have secret key or other delicate data to go to the server. The GET strategy has estimate constraint: just 1024 characters can be utilized in a demand string.

This data is passed utilizing QUERY_STRING header and will be open through QUERY_STRING condition variable and Servlet handles this kind of solicitations utilizing doGet() method.

POST Method

A for the most part progressively solid technique for passing data to a backend program is the POST strategy. This bundles the data in the very same route as GET strategy, yet as opposed to sending it as a content string after a ? (question mark) in the URL it sends it as a different message. This message goes to the backend program as the standard information which you can parse and use for your handling. Servlet handles this kind of solicitations utilizing doPost() method.

Reading Form Data utilizing Servlet

Servlets handles structure information parsing consequently utilizing the accompanying techniques relying upon the circumstance −

  • getParameter() − You call request.getParameter() technique to get the estimation of a structure parameter.

  • getParameterValues() − Call this strategy if the parameter seems more than once and restores different qualities, for instance checkbox.

  • getParameterNames() − Call this strategy in the event that you need a total rundown of all parameters in the current request.

GET Method Example utilizing URL

Here is a basic URL which will pass two qualities to HelloForm program utilizing GET method.

http://localhost:8080/HelloForm?first_name = ZARA&last_name = ALI

Given beneath is the HelloForm.java servlet program to deal with information given by internet browser. We are going to utilize getParameter() technique which makes it exceptionally simple to get to passed data −

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloForm extends HttpServlet {
 
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // Set response content type
      response.setContentType("text/html");

      PrintWriter out = response.getWriter();
      String title = "Using GET Method to Read Form Data";
      String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
         
      out.println(docType +
         "<html>\n" +
            "<head><title>" + title + "</title></head>\n" +
            "<body bgcolor = \"#f0f0f0\">\n" +
               "<h1 align = \"center\">" + title + "</h1>\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>"
      );
   }
}

Assuming your environment is set up properly, compile HelloForm.java as follows −

$ javac HelloForm.java

If everything goes fine, above compilation would produce HelloForm.class file. Next you would have to copy this class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/

<servlet>
   <servlet-name>HelloForm</servlet-name>
   <servlet-class>HelloForm</servlet-class>
</servlet>

<servlet-mapping>
   <servlet-name>HelloForm</servlet-name>
   <url-pattern>/HelloForm</url-pattern>
</servlet-mapping>

Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your browser's Location:box and make sure you already started tomcat server, before firing above command in the browser. This would generate following result −

Using GET Method to Read Form Data

  • First Name: Rocky
  • Last Name: Jhonson

GET Method Example Using Form

Here is a basic model which passes two qualities utilizing HTML FORM and submit catch. We are going to utilize same Servlet HelloForm to deal with this input.

<html> 

<body> 

<form action = "HelloForm" 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>

Keep this HTML in a record Hello.htm and place it in <Tomcat-installationdirectory>/webapps/ROOT registry. When you would get to http://localhost:8080/Hello.htm, here is the genuine yield of the above form.

First Name: Last Name:

Try to enter First Name and Last Name and after that click submit catch to see the outcome on your neighborhood machine where tomcat is running. In view of the info gave, it will produce comparative outcome as referenced in the above example.

POST Method Example Using Form

Let us do little alteration in the above servlet, with the goal that it can deal with GET just as POST techniques. The following is HelloForm.java servlet program to deal with info given by internet browser utilizing GET or POST methods.

//Import required java libraries
    
    
import java.io.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 

//Extend HttpServlet class 

public class HelloForm extends HttpServlet { 

//Method to deal with GET technique request. 

public void doGet(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException { 

//Set reaction content type 

response.setContentType("text/html"); 

PrintWriter out = response.getWriter(); 

String title = "Using GET Method to Read Form Data"; 

String docType = 

"<!doctype html open \"-/w3c//dtd html 4.0 " + 

"transitional//en\">\n"; 

out.println(docType + 

"<html>\n" + 

"<head><title>" + title + "</title></head>\n" + 

"<body bgcolor = \"#f0f0f0\">\n" + 

"<h1 adjust = \"center\">" + title + "</h1>\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>" 

); 

} 

//Method to deal with POST technique request. 

public void doPost(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException { 

doGet(request, response); 

} 

}

Now order and convey the above Servlet and test it utilizing Hello.htm with the POST technique as pursues −

<html> 

<body> 

<form action = "HelloForm" method = "POST"> 

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>

Here is the real yield of the above structure, Try to enter First and Last Name and after that click submit catch to see the outcome on your neighborhood machine where tomcat is running.

First Name: Last Name:

Based on the information gave, it would create comparative outcome as referenced in the above examples.

Passing Checkbox Data to Servlet Program

Checkboxes are utilized when more than one choice is required to be selected.

Here is model HTML code, CheckBox.htm, for a structure with two checkboxes

<html> 

<body> 

<form action = "CheckBox" method = "POST" target = "_blank"> 

<input type = "checkbox" name = "maths" checked = "checked" /> Maths 

<input type = "checkbox" name = "physics" /> Physics 

<input type = "checkbox" name = "chemistry" checked = "checked" /> 

Science 

<input type = "submit" value = "Select Subject" /> 

</form> 

</body> 

</html>

The consequence of this code is the accompanying form

Maths Physics Chemistry

Given beneath is the CheckBox.java servlet program to deal with information given by internet browser for checkbox button.

//Import required java libraries
import java.io.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 

//Extend HttpServlet class 

public class CheckBox extends HttpServlet { 

//Method to deal with GET strategy request. 

public void doGet(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException { 

//Set reaction content type 

response.setContentType("text/html"); 

PrintWriter out = response.getWriter(); 

String title = "Reading Checkbox Data"; 

String docType = 

"<!doctype html open \"-/w3c//dtd html 4.0 " + "transitional//en\">\n"; 

out.println(docType + 

"<html>\n" + 

"<head><title>" + title + "</title></head>\n" + 

"<body bgcolor = \"#f0f0f0\">\n" + 

"<h1 adjust = \"center\">" + title + "</h1>\n" + 

"<ul>\n" +
    
 " <li><b>Maths Flag : </b>: " 

+ request.getParameter("maths") + "\n" + 

" <li><b>Physics Flag: </b>: " 

+ request.getParameter("physics") + "\n" + 

" <li><b>Chemistry Flag: </b>: " 

+ request.getParameter("chemistry") + "\n" + 

"</ul>\n" + 

"</body>" 

"</html>" 

); 

} 

//Method to deal with POST technique request. 

public void doPost(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException { 

doGet(request, response); 

} 

}

For the above model, it would show following outcome −

Reading Checkbox Data

  • Maths Flag : : on
  • Physics Flag: : null
  • Chemistry Flag: : on

Reading All Form Parameters

Following is the nonexclusive model which utilizes getParameterNames() strategy for HttpServletRequest to peruse all the accessible structure parameters. This technique restores an Enumeration that contains the parameter names in an unspecified order

Once we have an Enumeration, we can circle down the Enumeration in standard path by, utilizing hasMoreElements() technique to decide when to stop and utilizing nextElement() strategy to get every parameter name.

//Import required java libraries 

import java.io.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 

import java.util.*; 

//Extend HttpServlet class 

public class ReadParams extends HttpServlet { 

//Method to deal with GET technique request. 

public void doGet(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException { 

//Set reaction content type 

response.setContentType("text/html"); 

PrintWriter out = response.getWriter(); 

String title = "Reading All Form Parameters"; 

String docType = 

"<!doctype html open \"-/w3c//dtd html 4.0 " + "transitional//en\">\n";
    
    out.println(docType + 

"<html>\n" + 

"<head><title>" + title + "</title></head>\n" + 

"<body bgcolor = \"#f0f0f0\">\n" + 

"<h1 adjust = \"center\">" + title + "</h1>\n" + 

"<table width = \"100%\" fringe = \"1\" adjust = \"center\">\n" + 

"<tr bgcolor = \"#949494\">\n" + 

"<th>Param Name</th>" 

"<th>Param Value(s)</th>\n"+ 

"</tr>\n" 

); 

Enumeration paramNames = request.getParameterNames(); 

while(paramNames.hasMoreElements()) { 

String paramName = (String)paramNames.nextElement(); 

out.print("<tr><td>" + paramName + "</td>\n<td>"); 

String[] paramValues = request.getParameterValues(paramName); 

//Read single esteemed data 

if (paramValues.length == 1) { 

String paramValue = paramValues[0]; 

if (paramValue.length() == 0) 

out.println("<i>No Value</i>"); 

else 

out.println(paramValue); 

} else { 

//Read various esteemed data 

out.println("<ul>"); 

for(int I = 0; I < paramValues.length; i++) { 

out.println("<li>" + paramValues[i]); 

} 

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

} 

} 

out.println("</tr>\n</table>\n</body></html>"); 

}
    //Method to deal with POST strategy request. 

public void doPost(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException { 

doGet(request, response); 

} 

}

Now, attempt the above servlet with the accompanying structure −

<html> 

<body> 

<form action = "ReadParams" method = "POST" target = "_blank"> 

<input type = "checkbox" name = "maths" checked = "checked" /> Maths 

<input type = "checkbox" name = "physics" /> Physics 

<input type = "checkbox" name = "chemistry" checked = "checked" /> Chem 

<input type = "submit" value = "Select Subject" /> 

</form> 

</body> 

</html>

Now calling servlet utilizing the above structure would create the accompanying outcome −

Reading All Form Parameters

Param Name Param Value(s)
maths on
chemistry on

You can attempt the above servlet to peruse some other structure's information having different items like content box, radio catch or drop down box etc.







© Javacodegeeks 2018 -
All Right Reserved and you agree to have read and accepted our term and condition.

Python 3