Building Servlets

Servlets extend a server program to enhance its functionality. One very common use for servlets is to extend a web server by providing dynamic web content. This posting shows how to create a very simple browser-based HTML form that executes a basic servlet to process user data that is entered onto the form.

The example was built with the following software configuration:

  • JDK1.8.0_45
  • Apache Tomcat v8.0.36
  • Eclipse Mars.2 Release (4.6.0)

About the Example

Web servers respond to browser requests with the HyperText Transfer Protocol (HTTP). HTTP is the protocol for moving hypertext files across the internet, and HyperText Markup Language (HTML) documents contain text that has been marked up for interpretation by an HTML browser such as FireFox.

A browser accepts user input through an HTML form. The simple form used in this lesson has one text input field for the user to enter text and a Submit button. When the user clicks the Submit button, the simple servlet executes and processes the user input. In this example, the simple servlet returns an HTML page that displays the text entered by the user.


Build in Eclipse

  1. Create a Dynamic Web Project
  2. Add HTML File to Project
  3. Add the Servlet to the Project
  4. Get Rid of Package Errors
  5. Code Overview
  6. Clean, Build, and Run the Example

1. Create a Dynamic Web Project

  1. In Eclipse, select File > New > Dynamic Web Project
  2. Name the project ServletProject and click Finish
  3. In the project , right click

2. Add HTML File to Project

  1. In the ServletProject, right click WebContent
  2. Select New > HTML File
  3. Name the HTML file index.html
  4. Click Finish
  5. Copy and paste the following code into index.html
  6. Add the Servlet to the Projecta
  7. Get Rid of Package Errors


The following HTML code displays the form shown here. When the user clicks the Click Me button on the form, the servlet gets the text entered and returns an HTML page with the text.



The HTML code has a POST method with an ACTION parameter where you specify the location of the servlet.

<!DOCTYPE html>
<meta charset="ISO-8859-1">
 <h2>I'm a Simple Form</h2>
 Enter some text and click the Submit button.
 <form method="POST" action="ExampServlet">
 <input type="text" name="data" size=30>
 <input type="SUBMIT" value="Click Me">
 <input type="RESET">

3. Add the Servlet to the Project

  1. Inside ServletProject, tight-click Java Resources
  2. Select New > Package
  3. Enter the package name, essentialsjpl and click Finish
  4. Right-click the essentialsjpl package
  5. Select New > Servlet
  6. Name the servlet ExampServlet and click Finish
  7. Copy the following code into the ExampServlet class file

The ExampServlet program builds an HTML page to return to the user. For this simple servlet, you need to import only the following packages:

  • for system input and output. The HttpServlet class uses the IOException class in this package to signal that an input or output exception has occurred.
  • javax.servlet, which contains generic (protocol-independent) servlet classes. The HttpServlet class uses the ServletException class in this package to indicate a servlet problem.
  • javax.servlet.http, which contains HTTP servlet classes. The HttpServlet class is in this package.
package essentialsjpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/ExampServlet"})
public class ExampServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
      PrintWriter out = response.getWriter();
    try {
      out.println("<body bgcolor=FFFFFF>");
      out.println("<h2>Button Clicked</h2>");
      String data = request.getParameter("data");
      if(data != null && data.length() > 0){ 
        out.println("Text Entered:");
      } else {
        out.println("No text entered.");
      out.println("<p>Return to <a href=
    } finally {            

4. Get Rid of Package Errors

If you see a bunch of package errors, it means you need to add the servlet container, as follows:

  1. Right-click ServletProject
  2. Select Properties
  3. Locate Targeted Runtimes in the left column
  4. Select Tomcat v8.0 (or which version you are using)
  5. Click Apply and OK

5. Code Overview

Annotations remove application configuration settings from the web.xml file and place them in the code where you can more easily manage them.

The example servlet uses the @WebServlet servlet annotation, which takes a URL as a parameter. The container uses the URL to determine the location of the servlet within a context to determine whether to forward a request to the servlet.

Class and Method Declarations

All HTML servlet classes extend the HttpServlet abstract class. Because HttpServlet is abstract, your servlet class must extend it and override at least one of its methods. An abstract class is a class that contains unimplemented methods and cannot be instantiated itself. You extend the abstract class and implement the methods you need so all HTTP servlets use a common framework to handle the HTTP protocol.

    public class ExampServlet extends HttpServlet {
           public void doPost(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException{

The ExampServlet class is declared public so that the web server that runs the servlet, which is not local to the servlet, can execute it.

The ExampServlet class defines a doPost method with the same name, return type, and parameter list as the doPost method in the HttpServlet class. The ExampServlet class overrides and implements the doPost method in the HttpServlet class.

The doPost method performs the HTTP POST operation, which is the type of operation specified in the HTML form used for this example. The other possibility is the HTTP GET operation, in which case you would implement the doGet method instead.

GET requests might pass parameters to a URL by appending them to the URL. A POST request might pass additional data to a URL by directly sending it to the server separate from the URL. A POST request cannot be bookmarked or emailed and does not change the URL of the response. A GET request can be bookmarked, emailed, and can add information to the URL of the response.

The parameter list for the doPost method takes a request and response object. The browser sends a request to the servlet and the servlet sends a response back to the browser. The doPost method implementation accesses information in the request object to find out who made the request, what form the request data is in, and which HTTP headers were sent. It also uses the response object to create an HTML page in response to the browser request. The doPost method throws an IOException if there is an input or output problem when it handles the request, and a ServletException if the request could not be handled. These exceptions are handled in the HttpServlet class.

Method Implementation

The first part of the doPost method uses the response object to create an HTML page. It first sets the response content type to be text/html, then gets a PrintWriter object for formatted text output.

 PrintWriter out = response.getWriter();
 out.println(“<body bgcolor=#FFFFFF>”);
 out.println(“<h2>Button Clicked</h2>”);

The next line uses the request object to get the data from the text field on the form and store it in the data variable. The getparameter method gets the named parameter, returns null if the parameter is not set, and returns an empty string if the parameter has no value.

String data = request.getParameter(“data”);

The next part of the doPost method gets the data out of the data parameter and passes it to the response object to add to the HTML response page.

    if(data != null && data.length() > 0){
    }else {
        out.println(“No text entered.”);

The last part of the doPost method creates a link to take the user from the HTML response page back to the original form and closes the response.

        out.println(“<P>Return to 
            <A HREF=../exampServlet.html>Form</A>”);

6. Clean, Build, and Run the Example

  1. Select Project > Clean
  2. Select Project > Build Project
  3. In the servers tab, right-click the server and select Add and Remove . . .
  4. Add ServletProject to the server
  5. Start the server
  6. Either open the Tomcat internal browser or a browser of your choice, and enter the following URL:

To open the Tomcat internal browser:

  1. Select Window > Show View > Other
  2. In the search box, type Internal
  3. Choose Internal Browser
    The Tomcat internal browser displays in Eclipse either along the bottom in the tabbed area on in the right pane.
Building Servlets

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s