Like doGet () method, the do Post () method is invoked by server through service () method to handle HTTP POST request. The doPost () method is used when large amount of data is required to be passed to the server which is not possible with the help of doGet () method.
In doGet () method, parameters are appended to the URL whereas, in do Post () method parameters are sent in separate line in the HTTP request body. The do Get ( ) method is mostly used when some information is to be retrieved from the server and the doPost () method is used when data is to be updated on server or data is to be submitted to the server. To understand the working of do Post () method, let us consider a sample program to define a servlet for handling the HTTP POST request.
A program to define a servlet for handling HTTP POST request
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class ServletPostExample extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
PrintWriter out = res.getWriter();
String login= req.getParameter(“loginid”);
String password= req.getParameter(“password”);
out.println(“Your login ID is: “);
out.println(login);
out.println(“Your password is: “);
out.println(password);
out.close();
}
}
The corresponding HTML code for this servlet is as follows
<HTML>
<BODY>
<CENTER>
<FORM NAME=”Form1″ METHOD=”post” ACTION=”https://ecomputernotes.com:8080/ServletGetExample”>
<B>Login ID</B> <INPUT TYPE=”text” NAME=”loginid” SIZE=”30″>
<P>
<B>Password</B> <INPUT TYPE=”password” NAME=”password” SIZE=”30″>
</P>
<P>
<INPUT TYPE=submit VALUE=”Submit”.>
</P>
</BODY>
</HTML>
This HTML code create as web page containing a form
Enter the required data and press the submit button on the web page. The browser will display the response generated dynamically by the corresponding servlet.