JAVA Servlet Program to implement and demonstrate get() and Post methods(Using HTTP Servlet Class).
Posted by MohammadYusuf
Last Updated: October 28, 2016

a. getpost.java File

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class getpost extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String s=request.getParameter("degree");
out.println("<h4>Its from get method</h4><br />");
out.println("<b><i>Contents attaced to URL</i></b><br />");
out.println("<b>Selected degree is: <b> "+s);
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String s=request.getParameter("lang");
out.println("<h4>Its from post method</h4><br />");
out.println("<b><i>Contents are not attached to URL</i></b><br />");
out.println("<b>Selected Programming language is: <b> "+s);
out.close();
}
}


b. getpost.html File

<html>
<head>
<title>Program to demonstrate get and Post methods</title>
</head>
<body>
<h3>Form for get method</h3><br/>
<form action="http://localhost:8080/examples/servlet/getpost" method="get">
<b> Select the degree </b><br/>
<input type="radio" name="degree" value="bba"/> BBA <br />
<input type="radio" name="degree" value="bca"/> BCA <br /><br/>
<input type="submit" value="OK(get)"/>
</form>
<hr/>
<h3>Form for post method</h3><br/>
<form action="http://localhost:8080/examples/servlet/getpost" method="post">
<b> Select the programming language </b><br/>
<input type="radio" name="lang" value="c"/> C <br />
<input type="radio" name="lang" value="java"/> Java <br /><br />
<input type="submit" value="OK(post)"/>
</form>
</body>
</html>