Vous êtes sur la page 1sur 43

TOMCAT and Servlets

Servlets 2.2

Accept application in standard format

Web Archive (WAR)

A web application is dened as a hierarchy of directories and les in a standard layout.


1

Such a hierarchy can be accessed in its unpacked form, where each directory and le exists in the lesystem separately, or in a packed form known as a Web ARchive, or WAR le. The top-level directory of your web application hierarchy is also the document root of your application When the system administrator deploys your application into a particular server, he or she assigns a context path to your application if the system administrator assigns your application to the context path /catalog, then a request URI referring to /cat-

alog/index.html will retrieve the index.html le from your document root.

TOMCAT Directories
.html, .jsp, etc. - The HTML and JSP pages, along with other les that must be visible to the client browser (such as JavaScript, stylesheet les, and images) for your application. /WEB-INF/web.xml - The Web Application Deployment Descriptor for your application. This is an XML le describing the servlets and other components that make up your application, along with any initialization parameters and containermanaged security constraints that you want the server to enforce for you. /WEB-INF/classes/ - This directory contains any Java class les (and associated resources) required for your application,
2

including both servlet and non-servlet classes, that are not combined into JAR les. If your classes are organized into Java packages, you must reect this in the directory hierarchy under /WEB-INF/classes/. For example, a Java class named com.mycompany.mypackage.MyServlet would need to be stored in a le named /WEB-INF/classes/com/mycompany/mypackage/M

/WEB-INF/lib/ - This directory contains JAR les that contain Java class les (and associated resources) required for your application, such as third party class libraries or JDBC drivers.

When you install an application into Tomcat (or any other 2.2/2.3-compatible server), the classes in the WEB-INF/classes/

directory, as well as all classes in JAR les found in the WEBINF/lib/ directory, are made visible to other classes within your particular web application. Thus, if you include all of the required library classes in one of these places (be sure to check licenses for redistribution rights for any third party libraries you utilize), you will simplify the installation of your web application no adjustment to the system class path (or installation of global library les in your server) will be necessary.

web.xml
As mentioned above, the /WEB-INF/web.xml le contains the Web Application Deployment Descriptor for your application. As the lename extension implies, this le is an XML document, and denes everything about your application that a server needs to know (except the context path, which is assigned by the system administrator when the application is deployed).

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?> <!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>

<!-- General description of your web application --> <display-name>My Web Application</display-name> <description>
4

This is version X.X of an application to perform a wild and wonderful task, based on servlets and JSP pages. It was written by Dave Developer (dave@mycompany.com), who should be contacted for more information. </description>

<!-- Context initialization parameters that define shared String constants used within your application, which can be customized by the system administrator who is installing your application. The values actually assigned to these parameters can be retrieved in a servlet or JSP page by calling:

String value = getServletContext().getInitParameter("name"); where "name" matches the <param-name> element of one of these initialization parameters. You can define any number of context initialization parameters, including zero. --> <context-param> <param-name>webmaster</param-name> <param-value>myaddress@mycompany.com</param-value> <description> The EMAIL address of the administrator to whom questions

and comments about this application should be addressed. </description> </context-param>

<!-- Servlet definitions for the servlets that make up your web application, including initialization parameters. With Tomcat, you can also send requests to servlets not listed here with a request like this: http://localhost:8080/{context-path}/servlet/{classname} but this usage is not guaranteed to be portable. It also makes relative references to images and other resources required by your servlet more complicated, so defining

all of your servlets (and defining a mapping to them with a servlet-mapping element) is recommended. Servlet initialization parameters can be retrieved in a servlet or JSP page by calling: String value = getServletConfig().getInitParameter("name"); where "name" matches the <param-name> element of one of these initialization parameters. You can define any number of servlets, including zero. -->

<servlet> <servlet-name>controller</servlet-name> <description> This servlet plays the "controller" role in the MVC architecture used in this application. It is generally mapped to the ".do" filename extension with a <servlet-mapping> element, and all form submits in the app will be submitted to a request URI like "saveCustomer.do", which will therefore be mapped to this servlet. The initialization parameter namess for this servlet are the "servlet path" that will be received by this servlet (after the filename extension is removed). The corresponding value is the name of the action class that will be used to process this request. </description>

<servlet-class>com.mycompany.mypackage.ControllerServlet</servlet-cla <init-param> <param-name>listOrders</param-name> <param-value>com.mycompany.myactions.ListOrdersAction</param-value> </init-param> <init-param> <param-name>saveCustomer</param-name> <param-value>com.mycompany.myactions.SaveCustomerAction</param-value> </init-param> <!-- Load this servlet at server startup time --> <load-on-startup>5</load-on-startup> </servlet> <servlet>

<servlet-name>graph</servlet-name> <description> This servlet produces GIF images that are dynamically generated graphs, based on the input parameters included on the request. It is generally mapped to a specific request URI like "/graph". </description> </servlet>

<!-- Define mappings that are used by the servlet container to translate a particular request URI (context-relative) to a particular servlet. The examples below correspond to the servlet descriptions above. Thus, a request URI like:

http://localhost:8080/{contextpath}/graph will be mapped to the "graph" servlet, while a request like: http://localhost:8080/{contextpath}/saveCustomer.do will be mapped to the "controller" servlet. You may define any number of servlet mappings, including zero. It is also legal to define more than one mapping for the same servlet, if you wish to. --> <servlet-mapping>

<servlet-name>controller</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>graph</servlet-name> <url-pattern>/graph</url-pattern> </servlet-mapping>

<!-- Define the default session timeout for your application, in minutes. From a servlet or JSP page, you can modify the timeout for a particular session dynamically by using HttpSession.getMaxInactiveInterval(). -->

<session-config> <session-timeout>30</session-timeout> <!-- 30 minutes --> </session-config>

</web-app>

Source Organization
A key recommendation of this manual is to separate the directory hierarchy containing your source code (described in this section) from the directory hierarchy containing your deployable application (described in the preceding section). Maintaining this separation has the following advantages: The contents of the source directories can be more easily administered, moved, and backed up if the executable version of the application is not intermixed. Source code control is easier to manage on directories that contain only source les.
5

The les that make up an installable distribution of your application are much easier to select when the deployment hierarchy is separate.

build.xml

<!-- A "project" describes a set of targets that may be requested when Ant is executed. The "default" attribute defines the target which is executed if no specific target is requested, and the "basedir" attribute defines the current working directory from which Ant executes the requested task. This is normally set to the current working directory. -->

<project name="My Project" default="compile" basedir=".">

<!-- ===================== Property Definitions ===================== <!--

Each of the following properties are used in the build script. Values for these properties are set by the first place they are defined, from the following list: * Definitions on the "ant" command line (ant -Dcatalina.home=xyz comp * Definitions from a "build.properties" file in the top level source directory * Definitions from a "build.properties" file in the developers home directory * Default definitions in this build.xml file

You will note below that property values can be composed based on the contents of previously defined properties. This is a powerful techni that helps you minimize the number of changes required when your deve environment is modified. Note that property composition is allowed w "build.properties" files as well as in the "build.xml" script. --> <property file="build.properties"/> <property file="${user.home}/build.properties"/>

<!-- ==================== File and Directory Names ================== <!--

These properties generally define file and directory names (or paths) affect where the build process stores its outputs. app.name Base name of this application, used to construct filenames and directories. Defaults to "myapp". app.version Version identifier for this application.

build.home The directory into which the "prepare" and "compile" targets will generate their output. Defaults to "build". catalina.home The directory in which you have installed

a binary distribution of Tomcat 4. be used by the "deploy" target.

This will

deploy.home The name of the directory into which the deployment hierarchy will be created, and into which the build directory will be copied. Defaults to "${catalina.home}/webapps/${app.name}". dist.home The name of the base directory in which distribution files are created. Defaults to "dist". --> <property name="app.name" value="myapp"/>

<property <property <property <property <property

name="app.version" name="build.home" name="catalina.home" name="deploy.home" name="dist.home"

value="1.0"/> value="build"/> value="../../../.."/> <!-- UPDATE THIS value="${catalina.home}/webapps/${app. value="dist"/>

<!-<!--

==================== Compilation Control Options ==============

These properties control option settings on the Javac compiler when i is invoked using the <javac> task.

compile.debug compile.deprecation compile.optimize -->

Should compilation include the debug option?

Should compilation include the deprecation optio Should compilation include the optimize option?

<property name="compile.debug" value="true"/> <property name="compile.deprecation" value="false"/> <property name="compile.optimize" value="true"/>

<!-- ==================== External Dependencies =====================

<!-Use property values to define the locations of external JAR files on your application will depend. In general, these values will be used two purposes: * Inclusion on the classpath that is passed to the Javac compiler * Being copied into the "/WEB-INF/lib" directory during execution of the "deploy" target.

Because we will automatically include all of the Java classes that To exposes to web applications, we will not need to explicitly list any dependencies. You only need to worry about external dependencies for files that you are going to include inside your "/WEB-INF/lib" direct

--> <!-- Dummy external dependency --> <!-<property name="foo.jar" value="/path/to/foo.jar"/> -->

<!-- ==================== Compilation Classpath ===================== <!--

Rather than relying on the CLASSPATH environment variable, Ant includ

features that makes it easy to dynamically construct the classpath yo need for each compilation. The example below constructs the compile classpath to include the servlet.jar file, as well as the other compo that Tomcat makes available to web applications automatically, plus a that you explicitly added. --> <path id="compile.classpath"> <!-- Include all JAR files that will be included in /WEB-INF/lib --> <!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** --> <!-<pathelement location="${foo.jar}"/> -->

<!-- Include all elements that Tomcat exposes to applications --> <pathelement location="${catalina.home}/common/classes"/> <fileset dir="${catalina.home}/common/lib"> <include name="*.jar"/> </fileset> <pathelement location="${catalina.home}/classes"/> <fileset dir="${catalina.home}/lib"> <include name="*.jar"/> </fileset> </path>

<!-- ==================== All Target ================================ <!--

The "all" target is a shortcut for running the "clean" target followe by the "compile" target, to force a complete recompile. --> <target name="all" depends="clean,compile" description="Clean build and dist, then compile"/>

<!-- ==================== Clean Target ==============================

<!--

The "clean" target deletes any previous "build" and "dist" directory, so that you can be ensured the application can be built from scratch. --> <target name="clean" description="Delete old build and dist directories"> <delete dir="${build.home}"/> <delete dir="${dist.home}"/> </target>

<!-- ==================== Compile Target ============================ <!--

The "compile" target transforms source files (from your "src" directo into object files in the appropriate location in the build directory. This example assumes that you will be including your classes in an unpacked directory hierarchy under "/WEB-INF/classes". --> <target name="compile" depends="prepare" description="Compile Java sources">

<!-- Compile Java classes as necessary --> <mkdir dir="${build.home}/WEB-INF/classes"/> <javac srcdir="src" destdir="${build.home}/WEB-INF/classes" debug="${compile.debug}" deprecation="${compile.deprecation}" optimize="${compile.optimize}"> <classpath refid="compile.classpath"/> </javac> <!-- Copy associated resource files --> <copy todir="${build.home}/WEB-INF/classes"> <fileset dir="src" includes="**/*.properties"/> </copy>

</target>

<!-- ==================== Deploy Target ============================= <!--

The "deploy" target copies the contents of the build directory into a location required by our servlet container, and picks up any external dependencies along the way. AFter restarting the servlet container, can now test your web application. -->

<target name="deploy" depends="compile" description="Deploy application to servlet container"> <!-- Copy the contents of the build directory --> <mkdir dir="${deploy.home}"/> <copy todir="${deploy.home}"> <fileset dir="${build.home}"/> </copy> </target>

<!-- ==================== Dist Target ===============================

<!--

The "dist" target creates a binary distribution of your application in a directory structure ready to be archived in a tar.gz or zip file Note that this target depends on two others: * "deploy" so that the entire web application (including external dependencies) will have been assembled * "javadoc" so that the application Javadocs will have been created --> <target name="dist" depends="deploy,javadoc" description="Create binary distribution">

<!-- Copy documentation subdirectory --> <copy todir="${dist.home}/docs"> <fileset dir="docs"/> </copy> <!-- Create application JAR file --> <jar jarfile="${dist.home}/${app.name}.war" basedir="${deploy.home}"/> <!-- Copy additional files to ${dist.home} as necessary --> </target>

<!-- ==================== Javadoc Target ============================ <!--

The "javadoc" target creates Javadoc API documentation for the Java classes included in your application. Normally, this is only require when preparing a distribution release, but is available as a separate target in case the developer wants to create Javadocs independently. --> <target name="javadoc" depends="compile" description="Create Javadoc API documentation"> <mkdir dir="${dist.home}/docs/api"/>

<javadoc sourcepath="src" destdir="${dist.home}/docs/api" packagenames="*"> <classpath refid="compile.classpath"/> </javadoc> </target>

<!-- ==================== Prepare Target ============================ <!--

The "prepare" target is used to create the "build" destination direct

and copy the static contents of your web application to it. If you n to copy static files from external dependencies, you can customize th contents of this task. Normally, this task is executed indirectly when needed. --> <target name="prepare"> <!-- Create build directory and copy static content --> <mkdir dir="${build.home}"/> <copy todir="${build.home}"> <fileset dir="web"/> </copy>

<!-- Copy external dependencies as required --> <!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** --> <mkdir dir="${build.home}/WEB-INF/lib"/> <!-<copy todir="${build..home}/WEB-INF/lib" file="${foo.jar}"/> --> <!-- Copy static files from external dependencies as needed --> </target>

</project>

Vous aimerez peut-être aussi