Ôªø Java and Tomcat on Mac OS X, Part I
Apple Developer Connection
Advanced Search
Member Login Log In | Not a Member? Support

Java and Tomcat on Mac OS X, Part I

Java Servlets on Mac OS X

For the past few years, Java has been gaining popularity as a server-side programming language. Java’s object-oriented nature and native network protocol handlers make it well suited for the web, especially for larger web applications. There are several ways to use Java in combination with your web servers, but the most popular methods involve Java servlets. Java servlets are extensions to a server, usually an HTTP (web) server, that allow developers to create custom dynamic applications. The most popular and stable servlet containers have long been available for Unix environments. With the introduction of the Unix-based Mac OS X, server-side Java is finally a serious option for web developers working on the Mac.

In this article, I’ll show you how to install and configure the Tomcat servlet container on your Mac OS X platform. Then I’ll describe how you can create and deploy some simple servlets and JavaServer Pages (JSPs). In Part II you‚Äôll see how to use Javaserver Pages (JSP) with Tomcat.

The Jakarta Tomcat Servlet Container

Tomcat is the Jakarta Project’s open-source servlet container and is released under the Apache Software Licence. Tomcat provides support for Java Servlet and JSP technologies. It’s a feature-rich platform with capabilities far beyond what we’ll discuss here. Once you’ve gone through this article and the following article, I encourage you to visit the Jakarta Tomcat Site to learn more.

Installing Tomcat on Mac OS X

Since Mac OS X comes standard with Java 2, installing Tomcat is a breeze. First, you’ll want to download a current stable binary release of Tomcat from http://jakarta.apache.org/site/binindex.html. At the time of this writing (summer 2001), the latest stable version of Tomcat was 4.0.1, so I have downloaded the file jakarta-tomcat-4.0.1.tar.gz.

Once you’ve downloaded the file, you’ll want to extract it into an appropriate directory, like /usr/local/. To install files into /usr/local/, you’ll need to give yourself administrator privileges via the sudo command. Also, if you don’t have gnutar, you’ll need to install it. It’s part of the Mac OS X Developer Tools.

liz@localhost:~> sudo sh
Password:
root@localhost:~> mv jakarta-tomcat-4.0.1.tar.gz /usr/local/
root@localhost:~> cd /usr/local/
root@localhost:local> gnutar -xzvf jakarta-tomcat-4.0.1.tar.gz 

That’s it. Tomcat is now installed under /usr/local/jakarta-tomcat-4.0.1/ — or a similar directory if you installed a different version. Please note that you will need to change the filenames and paths in the examples in this tutorial if your version or installation directory are different from mine.

Now you’ll probably want to change ownership of all the Tomcat files and directories to someone other than the administrator. Since I use the login “liz” on my system, I’m changing ownership of all files under jakarta-tomcat-4.0.1/ to “liz”.

root@localhost:local> chown -R liz:staff /usr/local/jakarta-tomcat-4.0.1

Starting and Stopping Tomcat

Tomcat expects certain environment variables to be defined before it starts. In order to simplify the startup and shutdown processes, you can create re-usable scripts. I usually store scripts like these in a directory called bin under my home directory. (That’s pretty standard in the Unix world.)

liz@localhost:~> mkdir bin
liz@localhost:~> cd bin
liz@localhost:bin>

Now you can create a file (using your favorite text editor, must be saved with unix line endings) called ~/bin/start_tomcat with the following contents:

#!/bin/sh
export CATALINA_HOME=/usr/local/jakarta-tomcat-4.0.1
export JAVA_HOME=/usr
$CATALINA_HOME/bin/startup.sh

And a file called ~/bin/stop_tomcat with these contents:

#!/bin/sh
export CATALINA_HOME=/usr/local/jakarta-tomcat-4.0.1
export JAVA_HOME=/usr
$CATALINA_HOME/bin/shutdown.sh

Finally, you must make these files executable:

liz@localhost:bin> chmod ug+x start_tomcat stop_tomcat 

Tomcat as a Stand-alone Service

Tomcat comes with a built-in HTTP server. By default, it runs as a stand-alone service on port 8080. You’ll learn how to use Tomcat with Apache below. If you’d rather use Tomcat by itself on port 80, you can change the port value in your server.xml file, as you’ll see shortly. For now, you can start Tomcat using the script you just created.

liz@localhost:~> ~/bin/start_tomcat

Now you can visit http://localhost:8080/ in your web browser to make sure things worked.

Tomcat Default Screen

If you are unable to connect to Tomcat, you can check for errors by examining your error log:

liz@localhost:~> cat /usr/local/jakarta-tomcat-4.0.1/logs/catalina.out 

Viewing the Example Servlets

Tomcat comes with several example servlets. If you used the above instructions to install Tomcat, you can view the examples by pointing your browser to http://localhost:8080/examples/servlets/

Custom Web Applications: Configuring Tomcat via server.xml

In order to deploy your own custom servlets, you will need to set a few parameters in the global configuration file, called server.xml. If you’ve followed the steps above for installing Tomcat, you’ll find the file at /usr/local/jakarta-tomcat-4.0.1/conf/server.xml. When you’re ready for an overview of all the directives in server.xml (and there are many), see your local Tomcat documentation at http://localhost:8080/tomcat-docs/config/index.html or go to http://jakarta.apache.org/tomcat/tomcat-4.0-doc/config/index.html. For now, however, you can follow the instructions in the section below to get up and running.

Creating and Deploying Servlets

Now you’re ready to deploy your own web applications. First, you’ll make some changes to your server.xml file in order to register your first custom application. In Java servlet lingo, a “Context” represents a web application. The Java Servlet Specification (version 2.2 or later) is fairly particular about the directory structure, which I’ll cover shortly. For more on Contexts, see your local Tomcat documentation at http://localhost:8080/tomcat-docs/config/context.html or visit http://jakarta.apache.org/tomcat/tomcat-4.0-doc/config/context.html.

In the example below, the application will be accessible via http://localhost:8080/mine (if you are running Tomcat as a stand-alone service on port 8080) or http://localhost/mine (if you are using Tomcat with Apache on the default HTTP port, 80). The files will live in /usr/local/jakarta-tomcat-4.0.1/webapps/mine.

Notice that the reloadable parameter for the new context is set to “true” for now. This means that servlets are automatically checked for changes, and are reloaded if necessary. If reloadable is “false”, you will need to re-start Tomcat each time you re-compile any class files. Reloading is a handy feature, but it causes a significant load on the server, and should be turned off once your web application has been launched and is viewable by the public.

<!-- you probably want to set "reloadable" 
to "true" during development, but you should 
set it to be "false" in production. -->

<Context path="/mine" docBase="mine" debug="0" reloadable="true">
  <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="localhost_mine_log." suffix=".txt"
    timestamp="true"/>
  </Context>

<!-- note that I've added this new context entry 
right above the pre-existing "Examples" context -->

<!-- Tomcat Examples Context -->

Now that you’ve added a new context, you’ll want to create the appropriate directories. For a more complete guide to the standard directory layout defined in the 2.2 Servlet Specification, see your local docs at http://localhost:8080/tomcat-docs/appdev/deployment.html or see http://jakarta.apache.org/tomcat/tomcat-4.0-doc/appdev/deployment.html. For now, however, I’ll guide you through a minimal installation that conforms to the standard. Create the following directories:

liz@localhost:~> cd /usr/local/jakarta-tomcat-4.0.1/webapps
liz@localhost:webapps> mkdir mine
liz@localhost:webapps> mkdir mine/WEB-INF
liz@localhost:webapps> mkdir mine/WEB-INF/classes
liz@localhost:webapps> mkdir mine/WEB-INF/lib

Now you need to create a new configuration file for your application. You can do this by copying an example configuration file into your new directory and making a few changes.

liz@localhost:webapps> cp ./tomcat-docs/appdev/web.xml.txt ./mine/WEB-INF/web.xml

Next you’ll make a few changes to your new web.xml file. First, set the display-name, description, and webmaster parameters to appropriate values for your application.

    <display-name>My Web Application</display-name>
    <description>
      Examples by Me
    </description>

[...]

    <context-param>
      <param-name>webmaster</param-name>
      <param-value>your@email.address</param-value>
      <description>
        The EMAIL address of the administrator to whom questions
        and comments about this application should be addressed.
      </description>
    </context-param>

Finally, add a Servlet Definition for your first servlet, along with a mapping so that the servlet can be viewed via a short URL.

    <servlet>
      <servlet-name>Hi</servlet-name>
      <description>
        Testing
      </description>
      <servlet-class>Hi</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Hi</servlet-name>
        <url-pattern>/Hi</url-pattern>
    </servlet-mapping>

“Hello World” servlet

Now you’re ready to create your first servlet. Create a file called webapps/mine/WEB-INF/classes/Hi.java with the following code:

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * My test servlet
 *
 * @author Liz Warner
 */

public class Hi extends HttpServlet {

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Hola</title>");
        out.println("</head>");
        out.println("<body bgcolor=\"white\">");
        out.println("<h1> Hi </h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

Compiling Servlets on Mac OS X

If you’re planning on creating anything but the simplest applications, I recommend that you use the Jakarta project’s Ant build tool. For the purposes of this tutorial, however, I’ll be compiling servlets the old-fashioned way, with the Java compiler (javac) that comes with Mac OS X.

In order to use javac, you’ll need to set up an environment variable called CLASSPATH, which contains paths to all the Java libraries you will need. (One advantage of using Ant is that you can avoid the CLASSPATH hassle by creating XML buildfiles for your projects which contain all the necessary parameters.)

This command will work if you’re using the bash or sh shells (Note: In order to insure proper wrapping in a variety of browsers, the following two commands include line breaks which must be removed before using them in a shell.):

liz@localhost:classes> export CLASSPATH="/System/Library/
Frameworks/JavaVM.framework/Versions/1.3/Classes/classes.jar:/usr/local/
jakarta-tomcat-4.0.1/common/lib/servlet.jar"

This command will work if you’re using the tcsh shell (if you’re not sure which you’re using, it’s probably tcsh):

liz@localhost:classes> setenv CLASSPATH "/System/Library/
Frameworks/JavaVM.framework/Versions/1.3/Classes/classes.jar:/usr/local/
jakarta-tomcat-4.0.1/common/lib/servlet.jar"

Now you should be ready to compile the servlet. You will also need to restart Tomcat so that your new web application will be recognized. If you are new to Unix-based environments, please note that javac is like many Unix commands in that it exits silently on success. In other words, if you don’t see any error messages, your .java file has been compiled successfully. I’ve added some ls commands to the listing below which you can use if you’d like to see that your .class file was created.

liz@localhost:classes> ls
Hi.java
liz@localhost:classes> javac Hi.java
liz@localhost:classes> ls
Hi.class Hi.java
liz@localhost:classes> ~/bin/stop_tomcat
liz@localhost:classes> ~/bin/start_tomcat

Now that Tomcat has restarted, you should be ready to load the servlet in your browser.

Servlet Screen Shot

Servlet to Process a Simple email Form

Now that you’ve learned how to create and deploy servlets, let’s work on something a little more interesting. This servlet, called “mail”, will send an email message to a recipient specified in the code. To register the servlet, you’ll want to modify the web.xml file for your web application one more time. These lines should look familiar:

    <servlet>
      <servlet-name>mail</servlet-name>
      <description>
        mail example
      </description>
      <servlet-class>mail</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>mail</servlet-name>
        <url-pattern>/mail</url-pattern>
    </servlet-mapping>

Now you can create a file called classes/mail.java that looks like this.

Once you’ve created the file, you can compile it using the javac command. If it won’t compile, don’t worry. You may need to add another library to your CLASSPATH variable with one of the following commands (depending on your current login shell). For sh or bash, here’s the command:

liz@mail:classes> export 
CLASSPATH="$CLASSPATH:/usr/local/jakarta-tomcat-4.0.1/common/lib/mail.jar"

For tcsh, it’s this:

liz@mail:classes> setenv 
CLASSPATH $CLASSPATH":/usr/local/jakarta-tomcat-4.0.1/common/lib/mail.jar"

Now when you visit http://localhost:8080/mine/mail, you should see your new servlet in action:

Mail Servlet Screen Shot
Mail Servlet Screen Shot

Conclusion

In this tutorial you’ve learned how to install and run the Jakarta Tomcat servlet container on your Mac OS X system, run some example servlets, and deploy your own web applications. In Part II you’ll see how you can use JavaServer Pages (JSP), and the Jakarta Project’s JSP Tag Libraries (Taglibs). Part II will also include an overview of Java database programming on Mac OS X using JDBC and MySQL.

More Information