Tomcat Introductory Tutorial

  • Uploaded by: Abhilash V Pillai
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Tomcat Introductory Tutorial as PDF for free.

More details

  • Words: 4,916
  • Pages: 15
Tomcat Introductory Tutorial This tutorial gives a brief overview of the servlet engine but for a thorough introduction to the application it is strongly advised that one reads the documentation that accompanies the application. This tutorial also serves to demonstrate how one builds a web application with the Tomcat technology by going through the paces of building a sample application. Tutorial Table of Contents Overview Tomcat and Servlets Developing Applications with Tomcat • • • • •

Installing Tomcat Deployment Organization Source Organization The Actual Development Process Integrating a Sample Application with Tomcat

Tomcat and Windows98

Introduction To Tomcat Overview Tomcat is the Reference Implementation for the Java Servlet 2.2 and JavaServer Pages 1.1 Technologies. It is the official reference implementation for these complementary technologies. Tomcat is a servlet container with a JSP environment. A servlet container is a runtime shell that manages and invokes servlets on behalf of users. Developed under the Apache license in an open and participatory environment, Tomcat is intended to be a collaboration of the best-of-breed developers from around the world. The latest release of this technology can be downloaded from this page.

Tomcat and Servlets As mentioned above Tomcat is the reference implementation for the Java Servlet 2.2 technology and obviously conforms to the specification that describes the programming environment that must be provided by all servlet containers that is documented in the Servlet API Specification, Version 2.2. This specification may be downloaded from this page.

This document may be used to understand the web application directory structure and deployment file (Chapter 9), methods of mapping request URLs to servlets (Chapter 10), container managed

security (Chapter 11), and the syntax of the web.xml, Web Application Deployment Descriptor (Chapter 13).

Developing Applications with Tomcat Installing Tomcat Deployment Organization Source Organization The Actual Development Process Integrating a Sample Application with Tomcat

Installation Tomcat will operate under any Java Development Kit (JDK) environment that provides a JDK 1.1 or JDK 1.2 compatible platform. The JDK is required so that your servlets, other classes, and JSP pages can be compiled. Once you have downloaded the required file, unzip it to a directory of your choice. (In the Microsoft Lab 5 at UWI the file is extracted directly to the C drive (C:\) ). A sub-directory named jakarta-tomcat is created and this is the root directory of the tomcat hierarchy. This sub-directory should contain the following directories as highlighted in the table below. A description of the directories is also given. Directory name

Description

bin

Contains the startup, shutdown, tomcat, ... scripts. These scripts are used to start and shutdown the server and also set the classpath and other environment variables.

conf

Contains various configuration files including server.xml (Tomcat's main configuration file) and web.xml that sets the default values for the various web applications deployed in Tomcat.

doc

Contains miscellaneous documents regarding Tomcat.

lib

Contains various jar files that are used by Tomcat. On UNIX any file in this directory is appended to Tomcat's classpath.

logs

This is where Tomcat places it's log files.

src

The servlet APIs source files. Don't get excited, though; these are only the empty interfaces and abstract classes that should be implemented by

any servlet container.

webapps

This is where we place our web applications. Usually contains sub-directories and the names usually indicates the respective web applications that are placed in the directory.

The following directories may also be present in the root directory of our Tomcat hierarchy structure: Automatically generated by Tomcat, this is where Tomcat places intermediate files (such as compiled JSP files) during work it's work. If you delete this directory while Tomcat is running you will not be able to execute JSP pages. You can create this directory to add additional classes to class the classpath. Any class that you add to this directory will es find it's place in Tomcat's classpath.

For a detailed review of the scripts and configuration files provided with Tomcat please take a look at the uguide\tomcat_ug.html file located in the doc directory.

Developing Applications with Tomcat Deployment Organization

Background Before describing how to organize your source code directories, it is useful to examine the runtime organization of a web application. Prior to the Servlet API Specification, version 2.2, there was little consistency between server platforms. However, servers that conform to the 2.2 specification are required to accept a Web Application Archive in a standard format, which is discussed further below. A web application is defined as a hierarchy of directories and files in a standard layout. Such a hierarchy can be accessed in its "unpacked" form, where each directory and file exists in the filesystem separately, or in a "packed" form known as a Web ARchive, or WAR file. The former format is more useful during development, while the latter is used when you distribute your application to be installed. The top-level directory of your web application hierarchy is also the document root of your application. Here, you will place the HTML files and JSP pages that comprise your application's user interface. When the system administrator deploys your application into a particular server, he or she assigns a context path to your application. Thus, if the system administrator assigns your application to the context path /catalog, then a request URI referring to /catalog/index.html will

retrieve the index.html file from your document root.

Standard Directory Layout To facilitate creation of a Web Application Archive file in the required format, it is convenient to arrange the files that Tomcat actually uses when executing your application in the same organization as required by the WAR format itself. To do this, you will have the following contents in your application's "document root" directory: •







*.html, *.jsp, etc. - The HTML and JSP pages, along with other files that must be visible to the client browser (such as JavaScript and stylesheet files) for your application. In larger applications you may choose to divide these files into a subdirectory hierarchy, but for smaller apps, it is generally much simpler to maintain only a single directory for these files. WEB-INF/web.xml - The Web Application Deployment Descriptor for your application. This is an XML file describing the servlets and other components that make up your application, along with any initialization parameters and container-managed security constraints that you want the server to enforce for you. This file is discussed in more detail in the following subsection. WEB-INF/classes/ - This directory contains any Java class files (and associated resources) required for your application, including both servlet and non-servlet classes, that are not combined into JAR files. WEB-INF/lib/ - This directory contains JAR files that contain Java class files (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-compatible server), the classes in the WEB-INF/classes/ directory, as well as all classes in JAR files found in the WEB-INF/lib/ directory, are added to the class path for 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 will be necessary.

Web Application Deployment Descriptor As mentioned above, the WEB-INF/web.xml file contains the Web Application Deployment Descriptor for your application. As the filename extension implies, this file is an XML document, and defines everything about your application that a server needs to know (except the context path, which is assigned by t he system administrator when the application is deployed). The complete syntax and semantics for the deployment descriptor is defined in Chapter 13 of the Servlet API Specification, version 2.2. Over time, it is expected that development tools will be provided that create and edit the deployment descriptor for you. In the meantime, to provide a starting point, a basic web.xml (text file) is provided in the doc/appdev. This file includes comments that describe the purpose of each included element.

Integration With Tomcat In order to be executed, a web application must be integrated with, or installed in, a servlet container. This is true even during development. We will describe using Tomcat to provide the execution environment. A web application can be deployed in Tomcat by one of three different approaches: •





Copy unpacked directory hierarchy into a subdirectory in directory %TOMCAT_HOME%/webapps/. Tomcat will assign a context path to your application based on the subdirectory name you choose. We will use this technique in the build.xml file that we construct, because it is the quickest and easiest approach during development. That is, if you choose your sub-directory in webapps to be students for your application it will be similar to your context path. Copy the web application archive file into directory %TOMCAT_HOME%/webapps/. When Tomcat is started, it will automatically expand the web application archive file into its unpacked form, and execute the application that way. This approach would typically be used to install an additional application, provided by a third party vendor or by your internal development staff, into an existing Tomcat installation. Add a entry in the Tomcat server.xml configuration file. This approach is described briefly below, and allows you to position the document root of your web application at some point other than the %TOMCAT_HOME%/webapps/ directory.

Integrating your app with other servlet containers will be specific to each container, but all containers compatible with the Servlet API Specification (version 2.2) are required to accept a web application archive file.

Developing Applications with Tomcat Source Organisation

Directory Structure A key recommendation is to separate the directory hierarchy containing your source code 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 files. The files that make up an installable distribution of your application are much easier to select when the deployment hierarchy is separate.

As we will see, the ant development tool makes the creation and processing of such directory hierarchies nearly painless. The actual directory and file hierarchy used to contain the source code of an application can be pretty much anything you like. However, the following organization has proven to be quite generally applicable, and is expected by the example build.xml configuration file that is discussed below. All of these components exist under a top level project source directory for your application: •

• •



etc/ - Directory containing special files related to your application that will be copied to the WEB-INF directory. In all cases, this will include the application deployment descriptor file (web.xml), but may include others as well. lib/ - Directory containing JAR files that will be copied to the WEB-INF/lib deployment directory. src/ - Java source files that generate the servlets, beans, and other Java classes required by your application. If your source code is organized into packages (highly recommended for large projects), the package hierarchy should be reflected as a directory structure underneath this directory. web/ - Directory containing the HTML files, JSP pages, and other resource files (such as JavaScript and stylesheet files) that will be accessible to browser clients. The entire hierarchy underneath this directory will be copied to the document root directory of your deployment home.

Build.Xml Configuration File We will be using the ant tool to manage the compilation of our Java source code files, and creation of the deployment hierarchy. Ant operates under the control of a build file, normally called build.xml, that defines the processing steps required. Like a Makefile, the build.xml file provides several "targets" that support optional development activities, such as creating the associated Javadoc documentation, erasing the deployment home directory so you can build your project from scratch, or creating the web application archive file so you can distribute your application. To give you a head start, a basic build.xml file is provided (in the doc/appdev folder) that you can customize and install in the project source directory for your application. This file includes comments that describe the various targets that can be executed. The following targets are generally provided: •





init - The initialization target is not executed directly. Instead, it is invoked indirectly (by virtue of a depends attribute) by all other build targets. This is a convenient place to create defaults for property values, which can be overridden by system properties on the command line that starts Ant. prepare - This target "prepares" the deployment directory, creating subdirectories as required. A common use of this target is to copy static files (documentation, HTML pages, and JSP pages) from the source directory to the deployment directory. When executed, this target will only create directories if they do not exist, and only copy files if the destination file does not exist, or the source version of the file is newer. This target is generally invoked indirectly, by virtue of a depends attribute on some other task. compile - This target is used to compile any source code that has been changed since the last time compilation took place. The resulting class files are created in the deployment directory, so that they can be directly executed when Tomcat is run. A cool feature of the Ant javac task is that it also copies any non-Java source files to corresponding places in the deployment directory,







while maintaining the appropriate package hierarchy. This is perfect for properties files that you reference as resource bundles. The "compile" target is generally defined as the default target for your project, so it will be executed when you simply type build. javadoc - This target creates Javadoc API documentation for the Java classes in this web application. The example build.xml file assumes you want to include the API documentation with your app, so it generates the docs in a subdirectory of the deployment directory. all - This target deletes the entire deployment directory and then recreates everything. It is a good habit to do this after you've made a bunch of changes, and before you check them in to your source code repository. In particular, you should perform build all before you use the "dist" target to create a distribution of your application, to ensure that the distribution contains no unwanted files. dist - This target creates a web application archive (WAR) file containing your application, and a JAR file containing all of the source code. In the example build.xml file, the contents of the WAR file are based on the most recent build in the deployment directory.

Batch Scripts The primary script we will utilize is generically called the build script. It executes Ant, which reads and processes the build.xml file discussed above. Each time you execute the build script, you will specify the build "target" that you wish to execute. Users of a command line MAKE tool (which processes a makefile) will recognize this approach. On Windows-based systems, the following script should be saved as file build.bat in the project source directory, and customzed as required: echo off rem Build Script for "My Application" rem $Id: source.html,v 1.2 2000/03/28 00:44:11 craigmcc Exp $ rem Identify the custom class path we need if "%CLASSPATH%" == "" goto noclasspath set _CLASSPATH=%CLASSPATH% set CLASSPATH=%CLASSPATH%;%TOMCAT_HOME%/classes goto restclasspath :noclasspath set _CLASSPATH= set CLASSPATH=%TOMCAT_HOME%/classes :restclasspath set CLASSPATH=%CLASSPATH%;%TOMCAT_HOME%/lib/ant.jar;%TOMCAT_HOME%/lib/xml.jar set CLASSPATH=%CLASSPATH%;%TOMCAT_HOME%/lib/jasper.jar set CLASSPATH=%CLASSPATH%;%TOMCAT_HOME%/lib/servlet.jar set CLASSPATH=%CLASSPATH%;%TOMCAT_HOME%/lib/webserver.jar rem Execute ANT to perform the requested build target java -Dtomcat.home=%TOMCAT_HOME% org.apache.tools.ant.Main %1 %2 %3 %4 %5 %6 %7 %8 %9 rem Clean up CLASSPATH set CLASSPATH=%_CLASSPATH% set _CLASSPATH=

Build script customizations you might consider include: • •

Setting the JAVA_HOME and TOMCAT_HOME environment variables (probably near the top of the script) if they are not defined already. Overriding properties defined in the build.xml file with default values. For example, to change the distribution home directory (property dist.home), you would include the following command line option after the word "java": -Ddist. home=xxxxx.

NB. The batch files found in %TOMCAT_HOME%\bin have been written and tested under Windows NT. Some modifications may be necessary for operation on a Windows 98 platform.

Developing Applications with Tomcat The Actual Development Process The following sections highlight the commands and tasks that you, as the developer of the code, will perform. The same basic approach works when you have multiple programmers involved, as long as you have an appropriate source code control system and internal team rules about who is working on what parts of the application at any given time.

Create Project Source Directory The first step is to create a new project source directory, and customize the build.xml and build script you will be using. The directory structure is described in the section labeled Source Organization, or you can use the sample application located in doc/appdev as a starting point.

Configure Tomcat to Recognize Your Application In order for Tomcat to recognize your application, you must integrate it as described in the section labeled Integration with Tomcat. Any of the proposed techniques can be used. For our purposes, we will assume that you are using the first approach (unpacked hierarchy), because we set the deployment home to be an appropriate directory under the %TOMCAT_HOME%/webapps directory.

Editing the Source and Building the Web Application One may make changes to any of the source files (java, html, scripts, etc) and once saved we are ready to build our web application. We compile the application by issuing the build command from

the project source root directory. The Ant tool will be utilized to compile any new or updated Java code. We do this once we have ensured that the following variables have been set: • •

The JAVA_HOME points at the base directory where you have installed the JDK (for example, c:\jdk1.2.2). The TOMCAT_HOME points at the base directory where you have installed Tomcat (for example, c:\jakarta-tomcat).

And the following have been done. • •

You have added directory %JAVA_HOME%/bin to your PATH environment variable, so that the java command is recognized and executed. Normally, any changes required to the CLASSPATH environment variable are handled for you by the development scripts. However, if you are defining your own scripts, you may need to add file %JAVA_HOME%/lib/tools.jar to your CLASSPATH.

Test Your Web Application To test your application, you will want to execute it under Tomcat. Assuming you have integrated your application as described earlier, this is very simple. Under Windows, execute: %TOMCAT_HOME%\bin\startup This command starts Tomcat as a background process. Now, point your web browser at the home page for your application, by opening the following URL (where "/myapp" is the context path you have assigned to it): http://localhost:8080/myapp Now, you can test your application to verify that it operates correctly. When you discover something that needs to change, fix it as follows: •



To change a JSP page, modify it in the source directory and then re-execute the build script. The updated page will be recopied, and Tomcat will recognize this the next time that page is accessed -- the page will then be recompiled automatically. Changing a servlet or other Java class is similar, but the effort required depends on whether you selected the "autoreload" attribute for this context when you integrated with Tomcat. First, edit the file in its source directory, and re-execute the build script. The updated Java class will be recompiled. If autoreloading is selected, Tomcat will notice this change the next time this class is referenced, and will automatically unload and reload your application. Otherwise, you will need to manually stop and restart Tomcat before continuing.

Do not forget to commit your changes to the source code repository when you have completed your testing!

Deploy Your Web Application When you are through adding new functionality, and you've tested everything, it is time to create the distributable version of your web application that can be deployed on the production server. The following general steps are required: • • •

Issue the command build all from the project source directory, to rebuild everything from scratch one last time. Issue the command build dist to create a distributable web application archive (WAR) file, as well as a JAR file containing the corresponding source code. Give the WAR file to the system administrator of your production server environment, so that he or she can install it.

NB. The batch files found in %TOMCAT_HOME%\bin have been written and tested under Windows NT. Some modifications may be necessary for operation on a Windows 98 platform.

Developing Applications with Tomcat Integrating a Sample Application with Tomcat NB. The batch files found in %TOMCAT_HOME%\bin have been written and tested under Windows NT. Some modifications may be necessary for operation on a Windows 98 platform.

If you surf to the following site and scroll to the bottom of the page you will see a hyperlink labeled Download Sample DataAccess Servlet. Click on the link and save the respected zip file to a directory on your drive. Now unzip the file to the same directory and you see the following files: • • • • • • •

shod\register\Student.java StudentDBServlet.java students.mdb index.html compile.bat StudentRegistration.html README_SETUP.html

Setting up the sample project folder We are going to create a directory within the webapps folder for our sample application and move the required source files to the respective directories.

1. Create a directory within the %TOMCAT_HOME%\webapps folder named student. 2. Browse (using Windows Explorer) to the %TOMCAT_HOME%\doc\appdev\sample folder and copy the contents of that folder to our student folder. We should have 3 sub-directories within our student folder now: web, etc and src and 3 build files, 1 .xml, a .bat(ch) file and .sh (linux). Delete the contents of the src and web directories. 3. Copy index.html and StudentRegistration.html to the web directory. 4. Copy the java source files to the src directory.

Required editing of files 1. Open the build.xml file in a text editor and change the following line property name="app.name" value="myapp"/ to read property name="app.name" value="student"/ (context path) 2. Open the build.bat file in a text editor also and add the following lines in the respective area: set CLASSPATH=%CLASSPATH%;%TOMCAT_HOME%\lib\jaxp.jar set CLASSPATH=%CLASSPATH%;%TOMCAT_HOME%\lib\parser.jar set CLASSPATH=%CLASSPATH%;%TOMCAT_HOME%\lib\jasper.jar set CLASSPATH=%CLASSPATH%;%JAVA_HOME%\lib\tools.jar 3. Open the index.html as well and change the href value of "/servlet/StudentDBServlet" to "student". student is the value of the url mapping we are going to give for our servlet in the servlet mapping specification in the web.xml file. See modifications of the web.xml file below. 4. Open the StudentRegistration.html file o change the action parameter value of the form tag to "student" instead of "/servlet/StudentDBServlet" o change the href value of "index.html" (near the end of the file) to "../student" 5. Open the StudentDBServlet.java file o Change line 145 from htmlBody += "
Return to Course Home Page"; To

htmlBody += "
Return to Course Home Page"; o

Change lines 194 and 195 from htmlPage += "
Return to Home Page | "; htmlPage += "View Student List"; To htmlPage += "
Return to Home Page | "; htmlPage += "View Student List";

6. Open the web.xml file and change to file to resemble the following: 7. <web-app> 8. Stduent Database Demo 9. <description> 10. This is a simple web application with a source code organization 11. based on the recommendations of the Application Developer's Guide. 12. 13. <servlet> 14. <servlet-name>StudentServlet 15. <servlet-class>StudentDBServlet 16. 17. <servlet-mapping> 18. <servlet-name>StudentServlet 19. /student 20. 21. 22. 23.Please note that the url-pattern value DOES NOT have to 24.be the same as the value for the app.name property in the build.xml file.

Building of the Web Application We now are ready to build our web application. 1. Open a command window and go to the project root directory. 2. Set the JAVA_HOME and TOMCAT_HOME variables. 3. Issue the build command to build the application. As a result of the build command our application is now built (once there are no errors) and you should see the following new folders, files in your application root directory: javadoc and Web-inf directories and index.html and StudentRegistration.html are now in the root directory of the sample application.

Testing the Application Before we can actually test our application via a web browser we need to set up the Data Source. Remember the Access database file from the zip file, well we are going to use that as our ODBC Data Source. Follow the instructions below:

1. From the Start menu, select Settings, then Control Panel and then double-click on the ODBC Data Sources icon. 2. This should bring up a window labeled ODBC Data Source Administrator and click the Add button. 3. We are now going to create a new data source. From the list of drivers displayed select the Microsoft Access driver and click Finish. 4. A window labeled ODBC Microsoft Access 97 Setup is displayed and in the text box labeled Data Source Name type StudentDatabase. Click the Select button and browse to the directory where you saved student.mdb. Select this database and click Ok. Click Ok again when the ODBC Microsoft Access 97 Setup window re-appears. 5. The ODBC Data Source Administrator window should re-appear and in the list of data sources displayed you should see the StudentDatabase data source that was just created. Click the Ok button to close the window and close the Control Panel window as well. Now that our data source is set up we can test our application. 1. Using the command window go to the %TOMCAT_HOME%\bin directory and start the Tomcat servlet engine by issuing the command startup. This opens a new window for the Tomcat servlet engine. To shutdown the engine we enter the command shutdown. 2. Now, point your web browser at the home page for your application, by opening the following URL http://localhost:8080/student

Tomcat and Window98 Running Tomcat on a Windows 98 Platform NB. The batch files found in %TOMCAT_HOME%\bin have been written and tested under Windows NT. Some modifications may be necessary for operation on a Windows 98 platform. Earlier in the tutorial you would have probably seen this message appear several times and muttered an "Oh no" to yourself. However the modifications that are to be made are indeed quite simple and in no time you can have Tomcat up and running on your Window 98 platform.

Modification Overview As mentioned earlier, some modification of the files that were distributed with the Tomcat application has to be done. Before we go any further there is a requirement that must be satisfied first for any modifications to be done. This is: •

Have the TextPad application installed, or



A suitably applicable file format conversion tool installed.

There are several files that are located in the %TOMCAT_HOME%\bin directory that have been saved with a UNIX file format. These are primarily the files we need to start and stop the Tomcat server and are as follow:• • • • • •

cpappend.bat jspc.bat shutdown.bat startup.bat tomcat.bat tomcatEnv.bat

The other file which must change its format is the build.bat file which is found in the root directory of our application (webapps/application). NB This file is used to build our web application. This UNIX format needs to be changed for the Windows 9x platform and without making this change if we try to run the files we get a Bad Command or Filename error being displayed.

Modification Process TextPad To modify these files using TextPad, open each respective file in the TextPad editor. Select File from the Menu bar and choose Save As. A pop-up window is displayed with the name of the file shown in a textbox labeled File name. This is to remain unaltered, however the only change we will make is to the File Format option. Select PC from the List box instead of UNIX. Click the Save button to save this change...and that is it. We are finished modifying the file format. Repeat the procedure for each file.

File Conversion Tool Use the respective conversion tool of your choice to change the files listed above from having a File Format value of UNIX to PC.

Modification Review That is all that is required to get your batch scripts working on a Windows 9x platform. Once these changes have been made you can build your web application and then start and stop your Tomcat server when testing the application. There is one other important concern when running the Tomcat application on the Windows 98 platform. This concern is that of Environment Space. If enough environment space has not been specified when running the batch scripts you may get an error stating "Not enough environment space" or something similar.

To solve this problem we must enlarge the environment space to enlarge the environment space we must set the following command in the CONFIG.SYS file. The CONFIG.SYS is found in your C directory (C:\). (This file is usually hidden so one must change the view properties in order to see it, or simply use the command window to edit the file) SHELL=C:\Windows\COMMAND.COM /P /E:4096 COMMAND.COM is found in the Windows installation directory (usually C:\windows). • •

/P means to leave COMMAND.COM running between commands (i.e, don’t exit when the user issues the dir command). /E: signifies how much environment space to reserve for each process. 4K is usually enough.

Related Documents

Tomcat
June 2020 10
Tomcat
November 2019 17
Tomcat
December 2019 9
Introductory
June 2020 17

More Documents from ""