View RSS Feed


Working with Java Servlets in Eclipse

Rate this Entry
by , 02-04-2012 at 06:56 PM (5566 Views)
Servlet is a Java program that runs on a web server to handle requests and returns response to clients. It is widely used for Java enterprise development, and Eclipse is one of the best IDE for Java development. So this article will walk you through a Java project using Eclipse IDE to create a web application that plays around with a Java servlet.

Set up Eclipse development environment
The following software programs are required to be installed on your computer:
  • Java JDK 7.0: This is the latest Java version at the time of writing this article. Download the JDK at:
  • Eclipse IDE for Java EE Developers (Eclipse Indigo, version 3.7). Download the latest version of Eclipse at:

    If you have Eclipse for Java Developers already installed, you have to install Web Tools Platform (WTP) in order to work with Java EE project. To install the WTP plug-in, select Help -> Install New Software… from Eclipse’s main menu. In the Install dialog, select “Indigo -” from the drop down Work with, and check “Web, XML, Java EE and OSGi Enterprise Development” from the list, then click Next. And you have to restart Eclipse after the installation completed.
  • Tomcat server: we will work with the latest version of Tomcat, 7.0. Download Tomcat 7.0 distribution at:

The project

We are going to build a simple but interesting web application. There is a web page that allows user to type a text and hit Submit button, the server will return an image with the text embedded at the center.

A quick introduction to Servlet

Here are some briefs about Java servlet you need to know:

  • A servlet is a Java program that runs on web server supports Java EE, such as Tomcat.
  • A servlet is just a Java class that extends the GenericServlet class or the HttpServlet class.
  • To handle client’s requests, the servlet class should override one of the following methods: doGet(), doPost(), doPut(), service()…However the doGet() and doPost() are the two methods which are commonly used.
  • The HttpServletRequest interface defines actions to work with client’s request.
  • To read data sent from the client (such as value of parameters or form fields), invoke method getParameter(String paramName) from an instance of the HttpServletRequest interface.
  • The HttpServletResponse interface defines actions to work with response to client.
  • To send output to the client, invoke methods on the ServletOutputStream object which is returned from HttpServletResponse.getOutputStream() method.
  • A servlet must be registered in the web deployment descriptor file (web.xml) in order to serve client’s requests.
  • A servlet can handle particular URL patterns through mapping in the web.xml file.
  • A serlvet has the following life cycle methods: init(), service() and destroy().
  • There is only one instance of a servlet created per web application.
  • Each client’s request is served by a separate thread.

Creating the project in Eclipse

Select File -> New -> New Project… from Eclipse’s main menu. In the New Project dialog, select Dynamic Web Project from the Web node:

Name:  new project 1.PNG
Views: 1727
Size:  19.6 KB
Figure: New project in Eclipse

Click Next, in the New Dynamic Web Project screen, type ImageServlet as Project name, leave others as default:

Name:  new project 2.PNG
Views: 1693
Size:  31.0 KB
Figure: Create new Dynamic Web project

Click Finish, the project is created with the following structure:

Name:  project structure 1.PNG
Views: 1712
Size:  11.6 KB
Figure: The project structure

Configure server runtime

Next, we need to add Tomcat 7.0 as the targeted runtime for our web application. The server runtime includes libraries and configuration that let us work with Java servlets. Select Project -> Properties from the main menu. In the dialog Project properties for ImageServlet, select the node Targeted Runtimes:

Name:  Targeted Runtime 1.PNG
Views: 1706
Size:  28.3 KB
Figure: Project Properties

Click New, the New Server Runtime Environment dialog appears. If Tomcat 7.0 is installed on your computer successfully, you will see it under the Apache node:

Name:  New Server Runtime Environment.PNG
Views: 1690
Size:  23.1 KB
Figure: Select Server Runtime

Select Apache Tomcat v7.0 from the list, and click Next. On the next screen, you need to specify the directory of your Tomcat’s installation:

Name:  New Server Runtime Environment 2.PNG
Views: 1698
Size:  17.7 KB
Figure: Configure Tomcat server

Click Browse to select the directory of Tomcat’s installation which is usually under: C:\Program Files\Apache Software Foundation\Tomcat 7.0 if you are using Windows.

Click Finish to close the New Server Runtime Environment dialog. You will see Apache Tomcat v7.0 is added to the screen Properties for ImageServlet:

Name:  New Server Runtime Environment 3.PNG
Views: 1700
Size:  29.2 KB
Figure: Tomcat is configured as a Target runtime

Check the Apache Tomcat v7.0, and click OK. The server runtime is now configured.

From the main menu, select Window -> Show View -> Servers to open the Servers view that allows us to work with the server and deploy the web application. Right click in the Servers view’s area, select New -> Server:

Name:  New Server.PNG
Views: 1672
Size:  9.3 KB
Figure: Create a new server

The New Server dialog appears, select Tomcat v7.0 Server under Apache node, then click Finish:

Name:  New Server 2.PNG
Views: 1682
Size:  25.6 KB
Figure: Define a new server

The server is now added to the Servers view:

Name:  New Server added.PNG
Views: 1673
Size:  6.9 KB
Figure: The Servers view

To test the server, right click on its name in the Servers view, select Start. You should see some logging information in the Console view indicates that the server is up and running.

Creating the Servlet

First, create a new package under which we will put our servlet class. In the Project Explorer view, right click on the src directory, select New -> Package. In the New Java Package dialog, type com.servlet.tutorial into the Name field, and click Finish.

Now, expand the node Deployment Descriptor:…, right click on the Servlets, select New -> Servlet:

Name:  Create Servlet 1.PNG
Views: 1719
Size:  25.0 KB
Figure: Create a new servlet

In the Create Servlet dialog, type com.servlet.tutorial into the field Java package, and type ImageServlet into the field Class name:

Name:  Create Servlet 2.PNG
Views: 1697
Size:  21.2 KB
Figure: Configure servlet information

Click Next. In the next screen, we can type description for the servlet in the Description field. The Initialization parameters section allows us to define init parameters for the servlet, however we don’t need this; the section URL mappings show all URL patterns that are mapped to the servlet. Eclipse automatically created the default one: /ImageServlet

Name:  Create Servlet 3.PNG
Views: 1724
Size:  19.3 KB
Figure: URL mapping for servlet

Click Next. In the next screen we can specify which methods from the HttpServlet class to be overridden. We implement only the doPost() method, so check the Inherited abstract methods and doPost:

Name:  Create Servlet 4.PNG
Views: 1671
Size:  21.7 KB
Figure: Select stub methods to implement

Click Finish. Eclipse creates the servlet class looks like the following:

Name:  Editor Servlet class.PNG
Views: 1874
Size:  25.4 KB
Figure: The generated Servlet code

As you can notice, the annotation @WebServlet("/ImageServlet") is added to the class ImageServlet:

  • @WebServlet is the annotation name.
  • /ImageServlet is the URL pattern which is mapped to this servlet.

Creating the JSP page

In order to call the servlet, we write a simple JSP page that contains only one text field and a button. Right click on the WebContent node, select New -> JSP File.

Name:  Create JSP file.PNG
Views: 1731
Size:  21.4 KB
Figure: Create a new JSP file

In the New JSP File dialog, type index.jsp as the File name, click Finish. Add the following code to the index.jsp page:

Java Code:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Text to Image</title>
        <form action="ImageServlet" method="post">
            Text <input type="text" name="imageText" size="30" /> <br>
            <br> <input type="submit" value="Submit" />

There is one thing should be noticed here: We specify ImageServlet as the form’s action. This name should map with the servlet mapping specified by the annotation @WebServlet("/ImageServlet"). Doing so our servlet will be invoked after the form is submitted.

Coding the Servlet

The servlet reads a text send from the user (via the form in the index.jsp page), embed the text into a specified image then return the image back to the user. The code is implemented in the doPost() method as follow:

Java Code:
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // get the text from user
        String text = request.getParameter("imageText");
        // place is image under WebContent
        String imageName = "MyCar.jpg";
        // get absolute path of the image
        String imagePath = getServletContext().getRealPath(imageName);
        // load the image

       BufferedImage image = File(imagePath));


       // specify the position to place the text

       int x = image.getWidth() / 3;

       int y = image.getHeight() / 3;


       // draw the text on the image

       Graphics graphic = image.getGraphics();


       graphic.setFont(new Font("Arial", Font.BOLD, 40));

       graphic.drawString(text, x, y);


       // return the image to client

       ImageIO.write(image, "jpg", response.getOutputStream());

Make sure you put the image file MyCar.jpg under the WebContent directory. The servlet will load the image from this location.

Run the project

We have done the coding part. Now let’s see how the application works by running it on Tomcat server. In the Servers view, right click on the server name, select Start. Open a browser window, then type the following URL into the address bar:

The port number may be different because it depends on your Tomcat’s configuration. You should see the following screen:

Name:  Run 1.PNG
Views: 1672
Size:  24.1 KB
Figure: Access the application home page

The page is displayed with a text field and a Submit button. Type some text, such as Lamborghini 2012, and hit Enter. You should see the following screen:

Name:  Run 2.PNG
Views: 1702
Size:  561.4 KB
Figure: Result after submitting form to the servlet

And voila! The image is added with the text we have typed. That indicates the servlet is running properly, as expected!

Packaging the application

A Java web application is commonly packaged as a web archive (WAR) file. A WAR file can be deployed on all web servers that support Java. Right click on the project name in the Project Explorer view, select Export -> WAR File… In the Export dialog, specify the path of the WAR file in the field Destination, then click Finish:

Name:  Export WAR.PNG
Views: 1695
Size:  18.4 KB
Figure: Generate a WAR file

So far you have been seeing some concepts about Java servlet and use Eclipse IDE to write an interesting web application that works with a servlet. You also understand how a servlet works throughout the example and how Eclipse IDE can be used to develop a Java web application.

Submit "Working with Java Servlets in Eclipse" to Facebook Submit "Working with Java Servlets in Eclipse" to Digg Submit "Working with Java Servlets in Eclipse" to Submit "Working with Java Servlets in Eclipse" to StumbleUpon Submit "Working with Java Servlets in Eclipse" to Google