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
-
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>
This form allows users to submit a username and a password to the /HelloWorld servlet.
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("");
}
This function handle user's POST requests.
-
Type a
username and a
password. Then click on
SubmitQuery.
The “HelloWorld” servlet will execute the
doPost function and return the received username/password.
Exercise
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.
Instead of using the form as in exercise 1, how do we send a GET request to the server by using
URL?
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.
(*) 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.
Back to top