Java Servlets   «Prev  Next»

Lesson 7 Using forms and servlets together
ObjectiveDescribes the Structure of a Servlet that uses Form Fields

Structure of Java Servlet that uses Form Fields

A Java Servlet that uses form fields often interacts with a form in a web page (HTML or JSP file). The Servlet can handle HTTP requests such as GET or POST that are made when a user submits the form.
Here's an example of a simple Java Servlet that handles form fields:
// Import necessary libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet("/formHandler")  // Annotation to define the Servlet URL
public class FormHandlerServlet extends HttpServlet {
    
    // Handling HTTP POST request
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        // Retrieve form data from request parameters
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        
        // Set the content type to HTML
        response.setContentType("text/html");
        
        // Get output writer
        PrintWriter out = response.getWriter();
        
        // Generate the HTML response
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>Form Submitted Successfully</h1>");
        out.println("<p>First Name: " + firstName + "</p>");
        out.println("<p>Last Name: " + lastName + "</p>");
        out.println("</body>");
        out.println("</html>");
    }
}

In this Servlet, the doPost() method is overridden to handle HTTP POST requests. This method is called by the server (via the service method) to allow a servlet to handle a POST request.
The HttpServletRequest object request is used to retrieve the form data. The getParameter() method is called with the name of a form field as an argument, and it returns the value of that field.
The HttpServletResponse object response is used to form the HTTP response that is sent back to the client. The getWriter() method returns a PrintWriter object that can send text data to the client. The various println() methods are then used to construct an HTML response that displays the submitted form data.
To use this servlet with a form, you'd simply have an HTML form whose action attribute is set to the servlet's URL (in this case, "/formHandler"), and which uses method="POST".






In a real-world application, form submissions would usually be more complex and might involve validation, database interaction, and other processing. Also, best practices, like avoiding cross-site scripting (XSS) by encoding output data, would need to be followed for security reasons.

Legacy CGI Programs

When you write a CGI program that interacts with a form, you actually create two files. One is the HTML for the form itself, and the other is the program that will process the form. When your business needs another field added, you have to change both files. On the other hand, when you use servlets with forms, everything can be in one file.

Using the METHOD Attribute

The METHOD attribute of the <FORM> tag can be either GET or POST. When you are writing a CGI program, it does not matter much which method you choose. When you write a servlet, you know that you can override doGet() to handle GET requests from the server. In the same spirit, you override doPost() to handle POST requests. Remember, if you type the name of the servlet in the URL, the browser will send a GET request to the server. Here is how servlet developers handle forms:
  1. When the browser sends a GET request, the server sends back the HTML for a form. The FORM tag attributes should be:
    1. The ACTION attribute should lead to this same servlet. For example, If you are writing a servlet called FormHello, the action is FormHello.
    2. METHOD attribute should be POST.
  2. When the browser sends a POST request, the servlet processes the form.

HTTP request method POST

Every web developer is familiar with the scenario in which a client fills out an HTML form and then submits the inserted information to a server-side program for processing. Some of these programs use the HTTP request method POST to deliver the data to the server-side program. The POST method sends the data to the server in the body of the request, rather than as a query string appended to a URL (as in the GET method). For example, consider the HTML form tag in the following example.

User Name:

Department:
Email:


When the client submits this form information, the top of the client's request text looks like this:
POST /project/controller HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword,
application/vnd.ms-powerpoint, application/vnd.ms-excel, application/pdf, */*
Referer: http://localhost:8080/project/login.jsp
Accept-Language: en-us
Content-Type: application/x-www-form-urlencoded
Beneath this text, after a few more headers, the body of the request carries the submitted data:
username=John+W+Smith&password=bw_p1967
JSPs and servlets make parsing the POST data quite transparent for the developer. This is the topic of the next few recipes. We then discuss how to use servlets and JSPs to post data so that they essentially play the role of client, instead of acting as a server-side program.
There is no rule in the servlet documentation that says you must do things this way, but almost all servlet developers do.
You keep your form HTML in the same file as the code that processes the file, and that makes changes simpler. In addition, you do not have to worry about someone loading your servlet with GET or POST, since your servlet sends valid responses to both methods.
See how to code doGet() in the next lesson.