Writing our first Servlet: Hello World

Programs must be written for people to read, and only incidentally for machines to execute ~ Abelson

Servlet are Java classes which service HTTP request and implement the javax.servlet.Servlet interface. Web application developers typically write servlets that extend
javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests

In our previous lesson we learnt how to link eclipse and web container and now we are ready to create our first Servlet program. I am going to show how to create a dynamic project and a servlet that say Hello World.Launch your eclipse, click on file and choose Dynamic Web Project. You will get a screen like the one shown below:

1

In the project name put henry tutorial. Do not change anything else and click finish. In project explorer, your project will look like this:

2

When you create a servlet it is supposed to go to Java resources. So to create our Hello world servlet. Select Henry Tutorial and right click on it and proceed to new. Click on the servlet and you you will get the following screen.

3

In the Java package put com.henrymbuguakiarie and class name put HelloWorld. So you have the following screen.

4

After you are done with changes click finish and you servlet will open in eclipse editor.

5

Put the code in the image above in your servlet and click save.
Now I want you to go back in your project explorer and expand your project tree like this:

6

To run our HelloWorld.java we need to right click on it select Run As and select Run on Server. If you are successful you will have the following result.

7
Congratulations, you just created your first servlet. Wishing you happy codding.

NB:If you get a server error while running your servlet. The problem could be your server start services when you boot your computer. The solution is to stop your server and run the servlet again. Am a Linux user, just launch your terminal and key in the following command to stop your server.
Sudo service tomcat6 stop. Go back to eclipse and run HelloWorld.java on the server.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s