Using doPost() in Java Servlets - PostServlet

Difference between doPost() and doGet()

When, we write method="get" in form action, doGet() is written in Servlets, if method="post", then doPost() is written. To better understand the difference, get is for submission of user data through url, whereas post is for submitting user data through non-url submission, invisible. This method is mostly used for carrying passwords and other confidential data which should not be visible in the address bar of your browser.

PostServlet - Folder Structure

       |_ postservlet
                   |_ index.html
                   |_ WEB-INF
                               |_ web.xml
                               |_ classes
                                         |_ PostServlet.class

PostServlet - index.html



<title>Post Servlet User Form</title>



<form action="/postservlet/ps" method="post">

Name: <input type="text" name="uname" width="20" />
Password: <input type="password" name="pass" width="20" />
<input type="submit" name="submit" value="Login" />




form: User input is taken in a form containing input fields.

action="/postservlet/ps"/ps is the url pattern in web.xml and the postservlet is the name of the project (folder name). The project folder name must be specified here for sure, else the statement means to search in the webapps directory but not within the project.

method="post": Invisible submission, at the background.

name="uname": Used to get the value in this field in Servlet class.

name="pass": Used to get the value in this field in Servlet class.

Post Servlet - web.xml









Can't understand web.xml? See Understanding web.xml in Java Servlets

import javax.servlet.http.*;
import javax.servlet.*;
public class PostServlet extends HttpServlet
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
String user=req.getParameter("uname");
String password=req.getParameter("pass");

PrintWriter pw=res.getWriter();

pw.println("<h1> Welcome "+user+"</h1> <br/>");
pw.println("<h2> Your Password is "+password+"</h2>");

javax.servlet.http.*: Contains HttpServlet, HttpServletRequest, HttpServletResponseclasses (used here).

javax.servlet.*: Contains ServletException (used here).*: Contains PrintWriter, IOException (used here).

doPost(): For url type submission, submission through url, observe method="post" in index.html
PrintWriter: Part of the package.

req.getParameter("uname"): Get the value (user input value) in the input field named uname.

req.getParameter("pass"): Get the value (user input value) in the input field named pass.

pw.println("<h1>Welcome "+user+"</h1> <br/>"): Present in the PrintWriter class, write Welcome along with user within <h1> with a line break. (here).

pw.println("<h2> Your Password is "+password+"</h2>"): Display password within h2 tag.

Note: Do not forget to compile the class and re/start tomcat! ;)

Posted by at on

Tags: Servlets,