Sie sind auf Seite 1von 11

Search

Advanced Search Log In | Not a Member? ADC Home > Internet & Web > Java > Support

Java Servlets on Mac OS X


For the past few years, Java has been gaining popularity as a server-side programming language. Javas objectoriented 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, Ill show you how to install and configure the Tomcat servlet container on your Mac OS X platform. Then Ill describe how you can create and deploy some simple servlets and JavaServer Pages (JSPs). In Part II youll see how to use Javaserver Pages (JSP) with Tomcat.

The Jakarta Tomcat Servlet Container


Tomcat is the Jakarta Projects open-source servlet container and is released under the Apache Software Licence. Tomcat provides support for Java Servlet and JSP technologies. Its a feature-rich platform with capabilities far beyond what well discuss here. Once youve 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, youll 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 jakartatomcat-4.0.1.tar.gz. Once youve downloaded the file, youll want to extract it into an appropriate directory, like /usr/local/. To install files into /usr/local/, youll need to give yourself administrator privileges via the sudo command. Also, if you dont have gnutar, youll need to install it. Its 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

Thats 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 youll 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, Im changing ownership of all files under jakarta-tomcat4.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. (Thats 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. Youll learn how to use Tomcat with Apache below. If youd rather use Tomcat by itself on port 80, you can change the port value in your server.xml file, as youll 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.

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 youve followed the steps above for installing Tomcat, youll find the file at /usr/local/jakarta-tomcat-4.0.1/conf/server.xml. When youre ready for an overview of all the directives

in server.xml (and there are many), see your local Tomcat documentation at http://localhost:8080/tomcatdocs/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 youre ready to deploy your own web applications. First, youll make some changes to your server.xmlfile 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 Ill cover shortly. For more on Contexts, see your local Tomcat documentation athttp://localhost:8080/tomcatdocs/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 restart 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 youve added a new context, youll 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 seehttp://jakarta.apache.org/tomcat/tomcat4.0-doc/appdev/deployment.html. For now, however, Ill 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 youll make a few changes to your new web.xml file. First, set the display-name, description, and webmasterparameters 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 youre 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 youre planning on creating anything but the simplest applications, I recommend that you use the Jakarta projects Ant build tool. For the purposes of this tutorial, however, Ill be compiling servlets the old-fashioned way, with the Java compiler (javac) that comes with Mac OS X. In order to use javac, youll 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 youre 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 youre using the tcsh shell (if youre not sure which youre using, its 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 dont see any error messages, your .java file has been compiled successfully. Ive added some ls commands to the listing below which you can use if youd 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 to Process a Simple email Form


Now that youve learned how to create and deploy servlets, lets 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, youll 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 youve created the file, you can compile it using the javac command. If it wont compile, dont 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, heres the command:
liz@mail:classes> export CLASSPATH="$CLASSPATH:/usr/local/jakarta-tomcat-4.0.1/common/lib/mail.jar"

For tcsh, its 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:

Conclusion
In this tutorial youve 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 youll see how you can use JavaServer Pages (JSP), and the Jakarta Projects 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

Java and Tomcat on Mac OS X, Part II

Apple products. Visit the Apple Store online or at retail locations.


Get information on 1-800-MY-APPLE Copyright 2011 Apple Inc.

All rights reserved. | Terms of use | Privacy Notice

Das könnte Ihnen auch gefallen