Hello World! – Servlets Tutorial using Eclipse IDE

**adsense_4x1Block**
Introduction


There are many Hello World! Servlet tutorials out there, but when I wanted to learn Servlets, none of these tutorials gave complete information, at least what should be given at that point to not just only create a Hello World Servlet, but to enable new comer to start thinking on the lines of how he can utilize power of Servlets in his own web project.


In this tutorial we will create our very first Servlet, and along the way develop some understanding about what Servlets are and how they play their role in a Java based Dynamic Web Project. If you are looking for a shorter hello world tutorial, then stop and search again.


Still there? Ok, Let’s have a quick 10,000 foot overview of Servlets in plain English, and develop some understanding for the scope of this tutorial:


  • Servlets are created for Java Web Projects. That is why Servlet Specification is part of JEE Platform (for Web Projects) rather than JSE Platform (for Desktop Projects).

  • A simple Java class when inherited from GenericServlet or any of its subclasses (normally HTTPServlet), inherits all the power that is built into Servlet API (Power of communicating with Web Server and doing stuff there).

  • You can think of Servlets as Plugins for the Web Server, on which your Web Project is going to be deployed. So with these plugins your application can perform custom actions (since you wrote these Servlets yourself) on the web server

  • When your web application is deployed, Web Server registers and loads all of your Servlet classes. So now web server knows what custom action to perform, when your application calls any of these Servlets.

With theses high level concepts, we are good to create our very first Servlet.



Step 1: Creating New Java Project

For this tutorial we will need a new Java Dynamic Web Project with an index.jsp page included as first landing page. If you are not comfortable with how to do that, I would recommend you to stop right here and complete this Hello World – JSP tutorial first.



Step 2: Adding a Servlet to your Web Project

Right click on project name in package explorer in Eclipse IDE, and select New > Servlet. ‘Create Servlet’ wizard will pop-up.

Wizard Screen 1:

Some project information is already filled. Let’s fill the blank fields.

Java Package: you can name your package anything. This name will be used for creating folder hierarchy under src folder in your project. Let’s say ‘servlets.hello’
Class name: Again your Servlet, your choice. I would suggest ‘HelloWorld’
Superclass: is by default set as ‘javax.servlet.http.HttpServlet’ since most of the time Servlets are used as HTTP request handlers on Web Servers (don’t worry I’ll explain it in a bit). However Servlets can be used on other Server types e.g. Mail or FTP Servers. Leave this field as is.

Eclipse Create New Servlet - Wizard Screen 1

Create New Servlet - Wizard Screen 1

You could press Finish, but let’s see what other options are available to customize our Servlet. Press Next button.

Wizard Screen 2:

Description: Enter anything useful that will describe your Servlet.
URL Mappings: Hm sounds interesting. I don’t know what it is. Let’s edit it to something else. Say “/HelloWorldMapping” (clicking on it will activate the Edit button). . don’t forget to put /

Eclipse Create New Servlet - Wizard Screen 2

Create New Servlet - Wizard Screen 2

Wizard Screen 3:

On third screen, all methods available to be implemented by our Servlet are listed. Since we are going to do a basic example, so let’s keep them to defaults i.e. doGet and doPost methods.

Eclipse Create New Servlet - Wizard Screen 3

Create New Servlet - Wizard Screen 3

Pressing Finish will do some stuff in background and IDE will open the newly created Servlet class.



Step 3: Making JEE Available – OPTIONAL

If you continued from “Hello World! – JSP” tutorial, or otherwise your Eclipse IDE has Tomcat Server configured, then you won’t see any error messages stating:

“The import javax.servlet cannot be resolved”

Since, Tomcat Server you have configured, already has ‘servlet-api.jar’ in its /lib folder therefore Eclipse won’t complain and it will find required jar in Project Build Path (Right Click on Project > Properties > Java Build Path > Libraries > Expand Tomcat’s Library).

When there are no errors reported by Eclipse, simply Skip this step and jump to Step 5.

Otherwise you will have to manually download and add Servlet support for your project. Reason being Servlets are part of Java Enterprise Edition (JEE) SDK Specification, thus we need to provide JEE binary (jar) to our web project. Here is how to do it.

Download JEE API binary distribution from any of these Maven repositories.

For Java EE 6: http://download.java.net/maven/2/javax/javaee-api/6.0/javaee-api-6.0.jar
For Java EE 5: http://download.java.net/maven/1/javaee/jars/javaee-api-5.jar

copying one of these javaee-api-x.x.jar to your java web project’s lib folder (Project/WebContent/WEB-INF/lib) and building your project (Eclipse > Project > Build Project ) will resolve these errors and add JEE Servlet capabilities to your project.

For those who are still wondering why this step was at all required here’s a pointer. In your generated Servlet class, it has:
‘extends HttpServlet’

The HttpServlet class, and much more are already compiled and packaged in javaee-api-x.x.jar we just added, so we and eclipse needed it to run our project.



Step 4: What has happened under the hood

Let’s see by adding blank Servlet, what changes are made to the project automatically by Eclipse. Knowing this is very important because advanced java technology tutorials will assume that you have done these steps when they ask you to add a Servlet.

servlets.hello.HelloWorld
Once wizard has finished, it opened the HelloWorld Servlet class. This class is created in src/servlets

hello/HelloWorld.java

This folder structure is created based on package name we provided on Wizard Screen 2

web.xml
Open WebContent/WEB-INF/web.xml file. With this new Servlet, two tags are added into web.xml file. and

1
2
3
4
5
6
7
8
9
10
11
  <servlet>
    <description>Servlet to print out Hello World!</description>
    <display-name>HelloWorld</display-name>
    <servlet-name>HelloWorld</servlet-name>
    <servlet-class>servlets.hello.HelloWorld</servlet-class>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>HelloWorld</servlet-name>
    <url-pattern>/HelloWorldMapping</url-pattern>
  </servlet-mapping>

As we know, this web.xml file is used by the Web Server (e.g. tomcat) to become aware of all the components of our Web Application. So upon startup, Tomcat will read this web.xml file and create a Servlet with this servlet-name as an instance of servlet-class.

Once Servlet is created, Tomcat will wait for any HTTP requests, which are addressed to this Servlet.

Here comes the second tag ‘servlet-mapping’, this actually helps tomcat to identify which HTTP requests are addressed to which Servlet. The url-pattern attribute is what we customized, so any request that has /HelloWorldMapping at the end, will be passed to this Servlet’s doGet or doPost methods.

HelloWorld.java
Let’s now look at default Servlet class generated for us by Eclipse. Here is how it looks like in effect (without comments)

package servlets.hello;

defines where this class is located in src folder.

1
2
3
4
5
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

These imports make required Servlet classes available for compiling. They are packaged inside servlets-api.jar (or javaee-api-x.x.jar if you downloaded that one), which provides contract implementation between your Web Server and Servlet class. Based on this contract between these two entites, Web Server can send information to Servlet and Servlet can communicate back in server understandable format.

1
public class HelloWorld extends HttpServlet

In Above line, ‘extends HttpServlet’ is what gives all the built in power of Servlets to your otherwise simple Java Class.

1
2
3
4
5
6
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
}

Above doGet and doPost methods will receive information from the Web Server, based on whether Request was a Get or a POST. Whenever server will realize some HTTP Request is addressed to this Servlet, server will create a HTTPServletRequest object, and pass it to one of these methods.

Web Server will also pass a HTTPServletResponse object to the Servlet, so that Servlet can do its custom processing, update or insert information in response object, and finish its processing. Server takes the control back, and based on updated response object, it will display the output in browser.

That is the contract implemented by javax.servlet packages.



Step 5: Customizing our Servlet with Hello World Message

Ok now we will quickly do some customizations and see how this all works.

Add this line of simple HTML code between body tags in index.jsp

1
<a href="HelloWorldMapping">Invoke Servlet</a>

Note: We will use only the ServletMappingString in link, and no need to append it with / since current jsp’s context URL will be automatically appended and resulting Request URL will be something like:

http://localhost:8080/Tut-ServletHelloWorld/HelloWorldMapping

Above link will simply generate an HTTP Get request. Which you have correctly guessed is URL Mapping for our Servlet. At the first sight of this URL, Tomcat will run to our Servlet, and hand him over the Request and Response objects to play with. HelloWorld Servlet will do some magic, update the response object and finish processing. Tomcat will get notified and it will simply draw that response on screen. (By the way, we can control this flow, but that is out of the scope of this tutorial).

Let’s add that magic logic in our Servlet. Add this snippet of code in doGet method stub. So it should look like:

1
2
3
4
5
6
7
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("Hello World!");
		out.close();
}

In these four lines of code, we are adding our customization to Tomcat’s Response Object for original Get Request. We set the content type of the response, so that browser can render it fine. Then we get the PrintWriter from response object (just implementation details, ignore them for now), and print a line to that stream. Finally we close the stream.



Step 6: Hello World Servlet in Action

We’ll now need to build our project prior to running it on server so that changes made in Servlet class are compiled.

From top Eclipse menu select Project > Build Project (If Build automatically is not selected in same menu. If it is, then no need to build manually and ignore this step.)

Right click on Project and select Run As > Run on Server. This will compile our Servlet class and launch index.jsp. Index page should contain simple html link to ‘HelloWorldMapping’.

Clicking on this html link will generate a request, which will go through the process explained above and return our custom response to browser.

Hello World Servlet Response in browser

Hello World Servlet Response in browser

There it is, a completely web server generated HTML page, using our Servlet of course.



Exercises:

  • Customize the Hello World message string to something else, say include your name in message and Right click on Project > Run As > Run on Server.

  • Include an html anchor tag (just like we added in our index.jsp), but this time point it to index.jsp rather than Servlet Name. See if you can link your Servlet generated html page back with index.jsp page.


    Let’s use these two lines:

    1
    2
    
    	out.println("</br>");
    	out.println("<a href='index.jsp'>Index Page</a>");