Servlets - Form Data


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

GET Method

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

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

The GET method is the default method to pass data from browser to web server and it creates a long string that shows up in your program's Location:box. Never utilize the GET method on the off chance that you have secret key or other delicate data to go to the server. The GET method 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 requests utilizing doGet() method.

POST Method

A for the most part progressively solid method for passing data to a backend browser is the POST method. This packages the data in the very same route as GET method, 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 browser as the standard methods which you can parse and use for your handling. Servlet handles this kind of requests utilizing doPost() method.

Reading Form Data utilizing Servlet

Servlets handles structure methods pass consequently utilizing the accompanying techniques relying upon the circumstance −

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

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

  • getParameterNames() − Call this method 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 browser utilizing GET method.

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

Given beneath is the HelloForm.java servlet browser to deal with methods given by internet browser. We are going to utilize getParameter() method 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 button. 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 button 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 modification in the above servlet, with the goal that it can deal with GET just as POST techniques. The following is HelloForm.java servlet browser 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 method 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 method 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 method 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 button to see the outcome on your neighborhood machine where tomcat is running.

First Name: Last Name:

Based on the methods 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 browser to deal with methods 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 method 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 method 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() method for HttpServletRequest to peruse all the accessible structure parameters. This method 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() method to decide when to stop and utilizing nextElement() method 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 method 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 method 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 methods having different items like content box, radio button or drop down box etc.







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

Python 3