Table of Contents

Servlet: handling a POST request

In this tutorial, we will create a simple HTML page which sends a POST request, including a username and a password to the “HelloWorld” servlet. The “HelloWorld” servlet will printout the received information.

Create a simple HTML page

  1. Open the servletlabs project in the previous tutorial.
  2. In the folder WebContent, create an form.html file with the following content:

    <html>
    <body>
    <form method="post" action="HelloWorld">
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input type="submit" />
    </form>
    </body>
    </html>
  3. This form allows users to submit a username and a password to the /HelloWorld servlet.
  4. Open the HelloWorld.java file, modify the doPost(…) function as the following:

    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		String userName = request.getParameter("username");
    		String password = request.getParameter("password");
     
    		response.setContentType("text/html");
    		PrintWriter pw = response.getWriter();
    		pw.println("<h2>");
    		pw.println("Username: "+userName);
    		pw.println("</h2><h2>");
    		pw.println("Inputed password: "+password);
    		pw.println("</h2>");
    		pw.println("");
    	}
  5. This function handle user's POST requests.
  6. Now, open http://localhost:8080/servletlabs/form.html on your web browser.
  7. Type a username and a password. Then click on SubmitQuery.


  8. The “HelloWorld” servlet will execute the doPost function and return the received username/password.


Exercise

  1. Inspired from this tutorial, create another form that send an integer number to a Servlet and get back the factorial of this number. Use GET method instead of POST.
  2. Instead of using the form as in exercise 1, how do we send a GET request to the server by using URL?
  3. Create another form that contains two text fields and two radio buttons named “rectangle” and “eclipse”. Then create a Java class that computes the area of a rectangle and an eclipse based on two input numbers. Finally, create a servlet that receives two numbers and an option from user, computes the corresponding area and returns the result to the user.
  4. (*) Create a Java class that interact with a database system (such as MySQL). Add to the database a list of student names. Implement a servlet and an HTML form that allows to list, add, update and delete a student name.