keyboardsamurais.de thoughts on software development, warts and all…

15Jan/0497

Tomcat Tutorial: HelloWorld for Complete Fools [English]

The following tutorial was translated into English from the German original on this site, which is also available here. Please excuse me for my poor english skills, I am not a native speaker.

Update 26.02.2007: Note, that this Article, though technically still relevant and valid, is not up to date with the progress of the eclipse platform. I created a screencast to reflect the changes that took place and to show you development with the Eclipse WTP. Click here for the article.

I know quite a number of java developers who, despite their good knowledge of the java platform, somehow failed to successfully deploy a new Servlet to a Apache Tomcat installation. I stress, that they did not fail because of their inferior skills, but because of the fact, that there is no comprehensive
resource out there that explains the Tomcat deployment procedure:

  • in a nutshell
  • with pictures
  • without going into details that aren't of direct interest

So, without much further ado, I will try to explain how to install tomcat, create a deployment structure using Eclipse and writing a simple HelloWorld Servlet.

In theory, deploying a Servlet is a really straightforward task - that is, if you know somebody who is willing to introduce you into the deployment mysticisms of the Apache Tomcat development. Unfortunately, I knew nobody who was really adroit with that. So I spent a really long time running into every single ambush Tomcat has to offer for blue eyed newbies. Hence I can rightly say, that Tomcat's configuration is a pain in the rear if you don't have an expert person who guides you through your very first steps. Even if you know your Google search words cold, you won't find a single document that makes your task seem trivial.

So I figured, it would be best for newbies and the like, if you could just follow an example with pictures in it. In the following tutorial, I will try to explain the deployment procedure from the very beginning in step-by-step fashion to build a standard "Hello World" Servlet. To accomplish this, I will use the Eclipse IDE and Eclipse specific plugins, but I hope that one can understand the general proceeding that is necessary for other IDEs as well. I will assume that you are familiar with the installation of eclipse and eclipse plugins.

The following software will be neccessary to follow the tutorial:

The Server

Especially for Windows users it's pretty easy to install Tomcat, because there it has a straightforward installer script that rids you of most of the configuration work. Everything you have to do is set the Administrator password (and remember it!) and the installation directory (and remember it!).

The Plugin

The Sysdeo Tomcat Plugin is our best friend. After you have installed it, you will notice these buttons and menues in your IDE.

The left button starts Tomcat, the middle button stops it, the right button restarts Tomcat. Right now, they won't work if you press them. To enable them, you first need to configure a few things. Go to the menu "Window-> Preferences" there, you will see this dialogue box.

Enlarge

Now you need to go to the menu item "Tomcat" and select your Tomcat version. At the time of writing that would be the 4.1 5.x version. Now we adjust the field "Tomcat Home" to point to the install directory that we selected before at install time. The Sysdeo plugin now knows where to look for the server.xml file and automatically assumes the standard path to look for the file. Eclipse is now able to manage this configuration file, i.e. add a new <context> for a new application.


The Tomcat servlet container, features multiple user roles, such as the "Administrator" that we have already added to the user configuration upon installation. All users and passwords are found (in plain text, so take care to handle this safely) in the conf/tomcat-users.xml file. We now need to add another user called "Manager" that was not added to the file at installation time. Therefor we scroll down the menu point "Tomcat" and click the item "Tomcat Manager App". Now we can add a username and a password for the manager. Subsequently we click on "Add user to tomcat-users.xml" and leave the configuration menu.


Enlarge
Now we are ready to test start our Tomcat server. Click on the start button in the Tomcat menu and watch the console output. If Tomcat boots up without any stacktraces open your browser, and try to open the following address http://localhost:8080/ . If you see an image
that is similar, to the one below everything is working okay. If it doesn't you might want to Google on what might have caused the stacktrace.

Hello World

For now, we stop out Tomcat server and take a look at our very own, first servlet. First, we need to open a new project in the navigator window.


In the project window we select "Tomcat Project"...

...click on the Next button and call our new project "Hello World"


After a click on the next Button we now can adjust under which URI (Uniform Resource Identifier) we want our new application to respond to our requests. To illustrate what part of the URL this is, just take a look at the fat part in the following address: http://localhost:8080/HelloWorld/hello.
The default adjustments on the other controls should be fine by now, so we don't bother to adjust them. They should look similar to following image.


Enlarge

If we now "Finish" the Wizard, we can see, that Eclipse has created a whole bunch of new directories. It should look similar to this:


Now we can create a new class named HelloServlet in the directory WEB-INF/src. Now we can copy and paste following code into this class.

import java.io.*;

import javax.servlet.http.*;
import javax.servlet.*;

public class HelloServlet extends HttpServlet {
  public void doGet (HttpServletRequest req,
                                         HttpServletResponse res)
        throws ServletException, IOException
  {
        PrintWriter out = res.getWriter();
        out.println("Hello, Brave new World!");
        out.close();
  }
}

Our View should now look like this:



Enlarge
Unfortunately we are not yet finished. We still need to create the web.xml descriptor, which contains certain elements of configuration specific to our application and the server behaviour. So we create the file web.xml in the directory WEB-INF (Note: not in the directory WEB-INF/src !!!). For our simple application, the following parameters should be fine.

<!DOCTYPE web-app PUBLIC
  '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN'
  'http://java.sun.com/dtd/web-app_2_3.dtd'>
<web-app>
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>HelloServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
</web-app>

What follows now is a little explanation of what we just copied and pasted into web.xml . The Doctype is an xml specific item that tells the xml parser where to look
for the dtd consistency rules for our xml document. The dtd ensures that no wrong parameter combinations are entered. The main tag &lt;web-app&gt; contains all preferences for our servlet. The &lt;servlet&gt; tag basically contains the name (&lt;servlet-name&gt;) that will be used throughout the xml document to reference our servlet and its linked class (&lt;servlet-class&gt;) . The tag &lt;servlet-mapping&gt; is responsible for telling the server, to what document name in the URL our application should respond to. Note, that the correct order of these tags has to be retained to form a valid web.xml descriptor. If we followed all steps correctly, we should now be able to fire up Tomcat again. Our workspace should now look like that:

Enlarge

So, if we now enter the right combination of URI and resource name into the address bar of our browser (in our case this would actually be http://localhost:8080/HelloWorld/hello) we should be able to see the output from our very first servlet. Congratulations, now you are in the game ;-)

Enlarge

Oh, yeah - if you want to enable your Tomcat engine to serve JSPs too, you just have to add the following lines to the web.xml file and put the jsp files in the top level directory of your eclipse project.

    <servlet>
        <servlet-name>jspAssign</servlet-name>
        <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
        <init-param>
            <param-name>logVerbosityLevel</param-name>
            <param-value>WARNING</param-value>
        </init-param>
        <init-param>
            <param-name>fork</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>3</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jspAssign</servlet-name>
        <url-pattern>/*.jsp</url-pattern>
    </servlet-mapping>

For further reading, I recommend following Sites:

Tomcat 4.1 Documentation
Advanced JSP and Servlet Tutorial

Filed under: Coding, Tutorial 97 Comments
   

Bad Behavior has blocked 718 access attempts in the last 7 days.

FireStats iconPowered by FireStats