You are on page 1of 60

Contenido

Contenido................................................................................................................................1
Chapter 1. Revision History....................................................................................................3
Chapter 2. Introduction...........................................................................................................4
2.1. Why Am I Writing This ?............................................................................................4
2.2. Copyright !icense and "ther Caveats.........................................................................4
2.3. What is Tomcat ?.........................................................................................................4
2.4. Why #hou$d I %se It ?..................................................................................................&
2.&. Tomcat 'ersions..........................................................................................................&
2.(. Tested )$at*orms...........................................................................................................(
Chapter 3. Insta$$ing Tomcat...................................................................................................+
3.1. )rere,uisites.................................................................................................................+
3.2. -o.n$oading The #o*t.are.........................................................................................+
3.3. Insta$$ing The #o*t.are................................................................................................/
3.4. #tarting and #topping Tomcat......................................................................................0
3.&. Running Tomcat as 1on2Root %ser...........................................................................13
Chapter 4. -ep$oying We4 App$ications..............................................................................12
4.1. Creating the He$$oWor$d #erv$et................................................................................12
4.2. -ep$oying 5He$$oWor$d5............................................................................................13
4.2.1. Creating the directory structure...........................................................................14
4.2.2. Creating the Conte6t -escriptor *i$e...................................................................1&
4.2.3. Creating a .e4.6m$ *i$e *or the .e4 app$ication.................................................1(
4.2.4. Copying the serv$ets 7#)s and support *i$es to their respective directories.......1+
4.3. #aying 5He$$oWor$d5.................................................................................................1+
4.4. -ep$oying 7ava #erver )ages.....................................................................................1/
Chapter &. Administering Tomcat.........................................................................................21
&.1. The Administration Too$ We4 Appp$ication.............................................................21
&.2. The 8anager We4 App$ication..................................................................................23
&.3. #tatus We4 App$ication..............................................................................................23
Chapter (. Customi9ing Tomcat...........................................................................................2&
(.1. -isa4$e -irectory !isting...........................................................................................2&
(.2. Custom -e*au$t )ages................................................................................................2(
(.3. Custom :rror )ages....................................................................................................2(
Chapter +. Tomcat Rea$ms....................................................................................................2+
+.1. :6ercise "vervie......................................................................................................2+
+.2. 7-;C Rea$m...............................................................................................................2/
+.2.1. Insta$$ and #etup the -ata4ase............................................................................2/
+.2.2. Insta$$ the 7-;C -river.......................................................................................20
+.2.3. #etting %p The -ata4ase Ta4$es.........................................................................20
+.2.4. Test The 7-;C -river and Connection..............................................................33
+.2.&. -ep$oy and Test the We4 App$ication................................................................33
+.2.(. )repare the 1ecessary !ogin and :rror HT8! <i$es.........................................33
+.2.+. :dit Tomcat=s server.6m$ To :na4$e 7-;C Rea$m.............................................32
+.2./. :dit the We4 App$ication=s .e4.6m$ To Re,uire Authentication.......................34
+.2.0. #tart Tomcat and Test.........................................................................................3(
Chapter /. Integrating Tomcat & and Apache 2....................................................................3/
/.1. %sing mod>?@2...........................................................................................................3/
/.1.1. Aetting the mod>?@2 connector...........................................................................3/
/.1.2. #erver :nvironment and #ystem Re,uirements..................................................3/
/.1.3. :6ercise "vervie...............................................................................................30
/.1.4. ;ui$ding mod>?@2................................................................................................43
/.1.4.1. Insta$$ Tomcat and veri*y that it is .or@ing proper$y..................................43
/.1.4.2. Insta$$ Apache 2 and veri*y that it is .or@ing proper$y...............................43
/.1.4.3. #hutdo.n 4oth Tomcat and Apache............................................................43
/.1.4.4. -o.n$oad compi$e and insta$$ the mod>?@2 source *i$es............................43
/.1.&. :dit Con*iguration <i$es httpd.con* ?@2.properties .or@ers2.properties and
server.6m$......................................................................................................................43
/.1.(. Con*iguring *or %1IB soc@ets............................................................................43
/.1.(.1. :nvironment 'aria4$es.................................................................................43
/.1.(.2. httpd.con*.....................................................................................................4&
/.1.(.3. ?@2.properties................................................................................................4&
/.1.(.4. .or@ers2.properties......................................................................................4&
/.1.(.&. server.6m$.....................................................................................................4(
/.1.(.(. Chec@ *or ?@2.shm........................................................................................4(
/.1.(.+. ?@2.soc@et )ermissions.................................................................................4+
/.1.(./. -ep$oying We4 App$ications.......................................................................4+
/.1.+. #tart Tomcat........................................................................................................4+
/.1./. #tart Apache........................................................................................................4+
/.1.0. 'eri*y that everything .or@s..............................................................................4/
/.2. Reverse )ro6y .ith Apache.......................................................................................4/
/.2.1. #ystem Re,uirements..........................................................................................4/
/.2.2. :6ercise "vervie...............................................................................................4/
/.2.3. :dit Tomcat=s server.6m$.....................................................................................40
/.2.4. :dit Apache=s httpd.con*.....................................................................................40
/.2.&. Testing Apache=s Reverse )ro6y.........................................................................&3
Chapter 0. Re*erences and %se*u$ !in@s...............................................................................&2
Appendi6 A. mod>?@2 434 :rror )ro4$em CWith He$p <rom Trevor ;ut$erD.......................&4
A.1. )ro4$em -escription..................................................................................................&4
A.2. Why does this happen?..............................................................................................&4
A.3. A #o$ution.................................................................................................................&&
Appendi6 ;. A4out the changes in .e4 app$ication dep$oyment section.............................&(
Appendi6 C. ;ui$ding mod>?@2 on Red Hat :nterprise !inu6 3 ERH:!F CContri4uted 4y
Andre. C$uteD.......................................................................................................................&+
Appendi6 -. :c$ipse Tomcat and the Tomcat -ep$oyer CContri4uted 4y )atricia GarstenD &0
Chapter 1. Revision History
Table 1-1. Revision History Table
18 June 2004
Revised web application deployment section completely, based on discussions
and contributions from Josh Rehman
18 June 2004 Updated version numbers of Tomcat in document
1! June 2004 "dded inte#ration with apache usin# Reverse $ro%y section
1! June 2004 "dded contribution by "ndrew &lute on buildin# mod'()2 on R*+, -
1! June 2004 "dded contribution by $atricia .arsten on usin# the Tomcat /eployer on +clipse
1! June 2004 &reditin# Trevor 0utler for resolvin# mod'()2 issues on 1andra)e
1! "pril 2004 &orrected ()2shm section
12 "pril 2004
Updated mod'()2 procedure for new 204 release $lease don3t use v202 for
mod'()2 if you can help it
21 1arch 2004 "dded "ppendi% 0 "lternative &onte%t /eployment 1ethod for Tomcat 4
14 1arch 2004 "dded "ppendi% " 404 +rror problems with 1andra)e "/56 server
22 7ebruary
2004
&ompleted J/0& Realm section
22 7ebruary
2004
7irst edition in8pro#ress uploaded
19 /ecember
200-
Re8formatted document in docboo) format for sin#le8source publishin#
12 1ay 200- :nitial Release of Tomcat 4
Chapter 2. Introduction
Tomcat, sometimes )nown as "pache Tomcat, sometimes as Ja)arta Tomcat, is a Java servlet
en#ine that is the reference implementation used by ;un for its Java servlet and J;$
specifications
2.1. Why Am I Writing This ?
" few years a#o, when : was wor)in# for a company that was an :01 business partner, one of
the thin#s : loved about :01 software products was the <=uic) ;tart< manual This manual
introduced the product throu#h a series of common tas)s, from installation to basic
confi#uration The manual did not #o deep into the details of the software 88 that3s what the User
>uides and other documentation were for 88 but it did help new users #et productive ?uic)ly,
and without scarin# them too much
The Ja)arta #roup produces a lot of documentation for Tomcat, but none of it seemed to be as
soothin#ly simple to read as the <=uic) ;tarts< : was used to *ence this document *opefully, :
have addressed the common issues facin# newbie Tomcat administrators in such a way that
their learnin# curve becomes easier to ne#otiate
2.2. Copyright, License and Other Caveats
This document is free documentation@ you can redistribute it andAor modify it under the terms of
the >BU >eneral $ublic ,icense as published by the 7ree ;oftware 7oundation@ either version 2
of the ,icense, or Cat your optionD any later version This document is distributed in the hope
that it will be useful, but E:T*FUT "BG E"RR"BTG@ without even the implied warranty of
1+R&*"BT"0:,:TG or 7:TB+;; 7FR " $"RT:&U,"R $UR$F;+ ;ee the >BU >eneral $ublic
,icense for more details
2.3. What is Tomcat ?
"ccordin# to its website, httpHAA(a)artaapacheor#Atomcat, "pache Tomcat is <the servlet
container that is used in the official Reference :mplementation for the Java ;ervlet and
Java;erver $a#es technolo#ies The Java ;ervlet and Java;erver $a#es specifications are
developed by ;un under the Java &ommunity $rocess<
" more detailed history can be found here
Java servlets are Java pro#rams that run on the server, and Java;erver $a#es or J;$s are ";$8
li)e scripts that use ta#s to implement data and functionality
2.4. Why ho!"d I #se It ?
: #et as)ed this ?uestion a lot There are faster servlet en#ines, and there are servlet en#ines
that are easier to administer, install, confi#ure and deploy There are - reasons why : use
Tomcat H
1 :t is free 7ree for commercial and non8commercial use under the "pache license This
means that if : need a server application to crunch data, and :3m wor)in# in a lar#e
corporation with no bud#et for software for my department, : can still #et this done,
le#ally
2 :t has a lar#e installed base of users This can be a real bonus, especially when you run
into trouble &hances are, someone somewhere has already encountered, and probably
fi%ed the problem you are facin# :f you are usin# proprietary software, people are not
so willin# to share e%pertise and you will probably end up shellin# out money to resolve
issues
- :t is a reference implementation Typically people e?uate this with <e%perimental< or
even <primitive< The #ood thin# about reference implementations is that, if you )now
how to deploy applications in this servlet en#ine, you should have no problems with
other servlet en#ines, commercial or otherwise "s lon# as the Java servlet en#ine is
<standards8compliant<, it should follow the same deployment steps, even if its
confi#uration method C>U: or te%t confi# filesD may be different
Ultimately, it is still your choice :f Tomcat or Java isn3t for you, or if you can afford a better
servlet en#ine, there3s no reason why you absolutely have to use Tomcat
2.$. Tomcat %ersions
Table 2-1. Tomcat Versions as of 30 January 2004
Servlet Specification JS Specification Tomcat Version
24 20 4024
2- 12 41-0
22 11 --2
2.&. Tested '"at(orms
: have tested the instructions in this document on the platforms below
Table 2-2. Teste! latforms
"peratin#
System
Java $evelopment %it Tomcat Version &pac'e Version
7edora &ore 2 :01 Java 2 v 141 ;R2 4024 2049
7edora &ore 1 :01 Java 2 v 141 ;R1 4018 2048
(f you are usin# Tomcat version ).0.24* up#ra!e no+ to ).0.2)* or apply t'e
'otfi, on t'e Ja-arta site. T'ere is a problem +it' session 'an!lin# in ).0.24 t'at
is resolve! by t'e 'otfi, an! t'e latest version of Tomcat.
(f you are usin# .e!ora /ore 2* you +ill nee! to install t'e up#ra!e -ernel-2.0.0-1.421
or better. T'e stoc- i020 -ernel t'at comes +it' t'e ./2 !istribution +ill 'an# your
system +'en anyt'in# Java is run on it. /'ec- your local yum repository for latest
up!ates.
Chapter 3. Installing Tomcat
This chapter covers downloadin# and installin# the Tomcat binaries on a ,inu% system
3.1. 'rere)!isites
0efore we be#in, we will need to have a Java 2 ;/. installed This document is based on the
:01 Java 2 ;/. v 141 Eith Tomcat 4, because of dramatic chan#es in ,inu% in the last year,
there are a few thin#s you will need to be aware of
:f you are usin# Red *at 9, 7edora &ore or any ,inu% distribution that uses the B$T, CBative
$F;:6 Thread ,ibraryD, you may have problems #ettin# Java to run properly :f you3re #ettin#
fre?uent se#mentation faults, you mi#ht want to turn off B$T, 1y advice is to #et the latest
versions of everythin#, that is, install version 141 of the Java 2 ;/. or better, and #et the 22
,inu% )ernel for superior performance
: will not cover the installation of the Java ;/. here : have a write8up on this 88 and how you
can turn off B$T, 88 at this location
There are si#nificant differences between Tomcat 4 and Tomcat 4
3.2. *o+n"oading The o(t+are
Gou can find the Tomcat binaries at H httpHAA(a)artaapacheor#AsiteAbininde%c#i ;croll to the
bottom of the pa#e to find the lin)s for Tomcat 4%, 4% and the web server connectors
Eith Tomcat 4, there are now ! files available for download :f you are runnin# ,inu%AUB:6, the
pac)a#e you are loo)in# for is the tarball, which at the time of this writin# is 4018 tar#I &lic)
on the lin) and your download should start automatically
Table 3-1. Tomcat ) ac-a#es as at 14 .ebruary 2004
ac-a#e 3ame "peratin# System Remar-s
(a)arta8tomcat8
4024tar#I
UB:6A,inu%
This is the base Tomcat pac)a#e The
servlet en#ine and startup scripts are in this
pac)a#e
(a)arta8tomcat840248
deployertar#I
UB:6A,inu%
This is the Tomcat /eployer pac)a#e The
deployer is for easily deployin# and
undeployin# web applications, especially if
you are usin# an :/+ ;ee the "ppendi% for
inte#ratin# the deployer with +clipse
(a)arta8tomcat840248
embedtar#I
UB:6A,inu%
This is the embedded Tomcat pac)a#e
JT0/K
(a)arta8tomcat84024e%e 1icrosoft Eindows
This is the installer for 1icrosoft Eindows
This probably wor)s on BT4A2000A6$ Bot so
sure about 94A98A1+ :f you )now, please
email me
(a)arta8tomcat84024Iip,
(a)arta8tomcat840248
deployerIip, (a)arta8
tomcat840248embedIip
EindowsAUB:6A,inu%
Gou can use this Iip file on UB:6A,inu%, but
you will have to remember to set the
permissions properly before it will wor)
Ehy #o to all that troubleL Just use the tar
pac)a#e
:f you are usin# Eindows, you have a choice of either the Iip file or the +6+ file : haven3t tried
runnin# Tomcat 4 on Eindows, so : cannot say anythin# else about it
3.3. Insta""ing The o(t+are
There are many ways that you can #et Tomcat installed on your ,inu% system Gou could use the
rpm3s that are now available on (pac)a#eor# or the tarballs from the Ja)arta site This
document covers only the Ja)arta tarballs : have never used the rpm pac)a#es before
:f you have already downloaded the binary, simply copy it to the directory you want to install it
under and e%pand the file 7or e%ample, if : downloaded the Tomcat tar file into
/home/someuser/downloads and wanted to install it under /opt, here is what : would do "s
root userH
# cp /home/someuser/downloads/jakarta-tomcat-5.x.xx.tar.gz /opt
# tar -zxvf jakarta-tomcat-5.x.xx.tar.gz
" directory called (a)arta8tomcat84%%% will be created and the Tomcat files will e%pand under
it
$reviously, : would have recommended that the jakarta-tomcat-5.x.xx directory be
renamed to (ust tomcat *owever, because : e%pect Tomcat 4 to be updated more fre?uently
for now, since it has only (ust been released, : would instead recommend creatin# a symbolic
lin) to a tomcat directory
# ln -s jakarta-tomcat-5.0.25 tomcat
:n order for Tomcat to startup and shutdown, you will also need to add an environment variable
pointin# to the Tomcat directory C&"T",:B"'*F1+D, and one variable pointin# to your Java ;/.
directory CJ"5"'*F1+D : will ma)e the followin# assumptionsH
J"5"'*F1+
Java is installed into /opt/IBMJava2-141
&"T",:B"'*F1+
Tomcat is installed into /opt/jakarta-tomcat-5.x.xx and symlin)ed to
/opt/tomcat
:nsert the followin# lines inside /etc/pro!le or /root/."ashrc
export JAVA_HOME=/opt/IBMJava2-141
export CATALINA_HOME=/opt/tomcat
Bow, save the file and reboot the system to ensure that all chan#es ta)e effect
3.4. tarting and topping Tomcat
0efore we be#in, we will need to ensure that &"T",:B"'*F1+ and J"5"'*F1+ are correctly
set To do this, we open a terminal and type the followin# H
# echo $CATALINA_HOME
# echo $JAVA_HOME
:f you #et a blan) line, or if the directory points anywhere besides where it is supposed to, you
will have to correct these environment variables first, before continuin#
:f everythin# is fine, you can start Tomcat with the followin# command "s root,
# $CATALINA_HOME/bin/startup.sh
To chec) if Tomcat is runnin# fine, you should open a browser and point the UR, to
httpHAAlocalhostH8080 Gou should see the default Tomcat welcome pa#e :t would be a #ood
idea, at this point, to browse the documentation or try out the e%ample servlets and Java;erver
$a#es samples
To stop Tomcat, as root,
# $CATALINA_HOME/bin/shutdown.sh
:f Tomcat does not start and you downloaded the Iip file, the cause is probably due to
permissions +nsure that the followin# files are e%ecutable H inside #$%&%'I(%)*+M,/"!n
directory,
# chmod +x startup.sh
# chmod +x shutdown.sh
# chmod +x tomcat.sh
"fter you have made the files e%ecutable, try startin# and stoppin# Tomcat a#ain
3.$. ,!nning Tomcat as -on.,oot #ser
: don3t believe there any issues with runnin# Tomcat as root user *owever, for the more
security8conscious readers out there, here are some instructions on runnin# Tomcat as a non8
root user
"t this sta#e, the Tomcat pac)a#es, files and binaries are owned by root Ee will first need to
create a Tomcat user and #roup that will own these files, and under which Tomcat will run
Tomcat 4ser 55 tomcat
Tomcat 6roup 55 tomcat
Bot too ima#inative, huh L Ee will now create the Tomcat user and #roup Fpen a terminal
window and, as root,
# groupadd tomcat
# useradd -g tomcat -d /opt/tomcat tomcat
# passwd tomcat
Botice that we specified the home directory of Tomcat to be AoptAtomcat ;ome people believe
that this is #ood practice because it eliminates an additional home directory that needs to be
administered
Bow, we will put everythin# in AoptAtomcat under Tomcat user and #roup "s root,
# chown -R tomcat:tomcat /opt/tomcat
:f /opt/tomcat is a symlin) to your Tomcat install directory, you3ll need to do thisH
# chown -R tomcat:tomcat /opt/jakarta-tomcat-5.x.xx
5erify that J"5"'*F1+ and &"T",:B"'*F1+ environment variables are setup for tomcat user,
and you should be #ood to #o Fnce the Tomcat binaries are under Tomcat user, the way you
invo)e it will be different
To start Tomcat,
# su - tomcat -c /opt/tomcat/bin/startup.sh
To stop Tomcat,
# su - tomcat -c /opt/tomcat/bin/shutdown.sh
"lso, be aware that your web applications will need to be deployed Cie copied to the web
application directoriesD as user tomcat, instead of root " little more hassle, but possibly a little
safer too
Chapter 4. Deploying We !pplications
" Java servletAJ;$ en#ine is not really useful without servlets and J;$s, and deployin# servlets
can sometimes be a difficult and error8prone process, because, in addition to writin# and
compilin# the servlet, you will need to edit at least 2 61, files to #et the servlet properly
deployed : will cover the manual method here, but there are other ways, such as usin# the
1ana#er Eeb "pplication or developin# an "nt build process There is also a deployer pac)a#e
that you can download : don3t )now how to use it thou#h :f you do )now, please email meM
Ee will write and compile a simple <*elloEorld< servlet and deploy it, usin# this e%ample to
<bootstrap< future deployments Ee need to test if the deployment environment is properly
setup, and try out some customiIation features, so we will )eep our first servlet simple to
familiariIe ourselves with the process
4.1. Creating the /e""oWor"d erv"et
7irst, open your favorite te%t editor or Java :/+ and create the followin# file H
7,ample 4-1. Hello8orl! Servlet
// Filename : HelloWorld.java
// Description : This servlet merely says hello!
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet ( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Hello, Cruel World!
</title></head>");
out.println("<body>");
out.println("<h1>Hello, Cruel World !</h1>");
out.println("This is my first servlet.");
out.println("</body>");
}// end doGet
}///:~
Bow, we save the file as *elloEorld(ava and compile it *ere, you will find the first of several
differences between Tomcat 4 and Tomcat 4
:f you3re li)e me, you normally use the servlet classes supplied by Tomcat to compile your
servlets, ta)e note that the filename of the pac)a#e has chan#ed H it is now called servlet-
ap!.jar, not servlet.jar, as it was previously C "m : wron# L ,et me )now M D
:f you don3t )now what :3m tal)in# about, (ust compile the servlet usin# the followin# commandH
# javac -classpath $CATALINA_HOME/common/lib/servlet-api.jar
HelloWorld.java
To avoid havin# to )ey in the <classpath< switch every time, (ust include the servlet8api(ar
pac)a#e inside your &,";;$"T* That is,
export CLASSPATH=$CLASSPATH:$CATALINA_HOME/common/lib/servlet-api.jar
Gour servlet should compile cleanly without errors, but if you do, chec) the synta% in your source
code :f you (ust cut and pasted my code above, you should not #et any errors
:f your compile completed successfully, you should see a file called *ello-orld.class inside
the same directory Gou are now ready to proceed to deployin# your first servlet
4.2. *ep"oying 0/e""oWor"d0
$eployin# & 8eb &pplication
/eployment of a web application in Tomcat consists of the followin# tas)s H
1 &reatin# the directory structure
2 &reatin# the &onte%t /escriptor file
- &reatin# a web%ml file for the web application
4 &opyin# the servlets, J;$s and support files to their respective directories
4.2.1. Creating the directory structure
0efore you be#in deployment, you will need to create a directory structure under the
#$%&%'I(%)*+M,/we"apps directory that conforms to the servlet specifications 7or our
e%ample <*elloEorld< servlet, we are #oin# to create a directory called <1y7irst<, and we are
#oin# to save our <*elloEorld< servlet under that directory
"s tomcat user,
$ cd $CATALINA_HOME/webapps
$ mkdir MyFirst
$ mkdir MyFirst/WEB-INF
$ mkdir MyFirst/WEB-INF/classes
$ mkdir MyFirst/WEB-INF/lib
Gou should #et a directory structure similar to the one belowH
/irectory structure of a new web application
" little e%planation may be helpful at this point The directory structure is important to the
servlet en#ine The purposes of the various directories are shown below H
Table 4-1. 8eb &pplication $irectory Structure
A1y7irst
This is the web applications root directory This is analo#ous to a directory in
the "pache webserver, in that you will put your static *T1, files, ima#e files
C#if, (p#, etcD and Java;erver $a#es CJ;$sD here :f you have an inde%html file
in this directory, the UR, used in a browser to view it is
httpHAAhostnamedomaincomH8080A1y7irstAinde%html Gou can create a
subdirectory here that stores other *T1, files or ima#e files
A1y7irstAE+08
:B7
This is where your web application3s confi#uration file web%ml will #o
A1y7irstAE+08
:B7Aclasses
This is where the servlets that ma)e up your web application should be copied
or saved
A1y7irstAE+08 :f your application re?uires additional support libraries, for e%ample J/0&
:B7Alib drivers, they should be copied here
To illustrate this #raphically, our final web application should be laid out as shown belowH
/irectory structure of a new web application
4.2.2. Creating the Conte"t Descriptor #ile
T'is section 'as been revise! an! is !ifferent from ol!er versions of t'is !ocument. See
t'is &ppen!i, for an e,planation of t'e c'an#es.
The conte%t descriptor file, accordin# to the Tomcat official documentation, is <used to define
Tomcat specific confi#uration options, such as lo##ers, data sources, session mana#er
confi#uration and more<
The file follows an 61, synta%, and the name of the file is always the name of the web
application, with a .xml e%tension ;o, for this application, called M./!rst, the name of the
conte%t descriptor is M./!rst.xml
&reate a file called M./!rst.xml with the followin# contentsH
<!-- MyFirst Context -->
<Context path="/MyFirst" docBase="MyFirst" debug="0" reloadable="true"/>
;ave the file into #$%&%'I(%)*+M,/con/$atal!na/localhost/ directory
Eith much older versions of Tomcat, such as the early Tomcat -% series or 40% series, you
had to add the N&onte%tO definitions inside server.xml :f you are readin# an older version of
my article, you may notice that : still described the server.xml method Eith Tomcat 4%, the
conte%t descriptor provides a cleaner separation of web application confi#uration and the main
Tomcat server confi#uration "n added benefit is that web applications deployed in this way do
not re?uire a stop and restart of the Tomcat server process Tomcat should automatically pic) it
up while it is still runnin#
4.2.3. Creating a $e."ml #ile #or the $e application
The file web%ml is sometimes )nown as a deployment descriptor, and it is basically the
confi#uration file for your web application :n this file, you determine, amon# other thin#s H
the UR, of the servlets in your web application
the authentication method you wish to use
Gour filter definitions
7or now, we will simply re#ister *ello-orld as a servlet in the web application called
M./!rst Ee create a new we".xml file with the followin# contents inside it H
<?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>
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
Gou will notice that we had to do two thin#s here H
"ssociate the servlet class file Cin this case, *elloEorldclassD with a handler
C*elloEorldD
/efine how the servlet is accessed via a UR,
:n previous releases of Tomcat, if you did not define the Nservlet8mappin#O element, you could
still invo)e the servlet by typin# httpHAAhostnamedomaincomA1y7irstAservletA*elloEorld "s of
version 4118, this option is turned off, and you will have to define your servlet3s UR:
:n the we".xml file we (ust created, we told Tomcat that the servlet called *ello-orld.class
is referred to as *ello-orld, and that the UR, by which this servlet is to be referred to is
httpHAAhostnamedomaincomH8080A1y7irstA*elloEorld
4.2.4. Copying the servlets% &'(s and support #iles to their respective
directories
Bow we can copy the Java class file that we compiled earlier, into the deployment directory
0ecause this is a servlet, it will #o into #$%&%'I(%)*+M,/we"apps/M./!rst/-,B-
I(//classes directory There is no need to copy the source file into that directory
7or more complicated deployments, such as servlets that re?uire additional classes, such as
J/0& drivers, or libraries, these additional files must be stored inside the /-,B-I(//l!"
subdirectory of the web application directory :f you wish to ma)e these libraries available to all
web applications in Tomcat, save them inside #$%&%'I(%)*+M,/common/l!"/ directory
7or Java;erver $a#es CJ;$sD, the P(sp files #o in the same directory as the static *T1, files,
that is, under #$%&%'I(%)*+M,/we"apps/M.)-e")%ppl!cat!on/
4.3. aying 0/e""oWor"d0
Testin# your servlet
Ee are now ready to test our *elloEorld servlet ;ince this is the first servlet we are testin#,
and we are not really sure what we will see, : stron#ly advise #oin# into 6 Eindows and openin#
several terminal windows to display error and information messa#es, as they occur *ere3s how
we3re #oin# to test and see if our Tomcat deployment can indeed say <*elloEorld< M
1 ;tart 6 Eindows and the des)top environment of your choice
2 ,o# in as root
- Fpen - terminal windows
4 :n the first terminal window, e%ecute the followin# commands H
# cd $CATALINA_HOME/bin
# ./startup.sh
4 :n the second terminal window, e%ecute the followin# commands H
# cd $CATALINA_HOME/logs
# tail -f catalina.out
This will display the messa#es that Tomcat writes to the lo# file catalinaout, which is
automatically created, if it does not already e%ist
2 :n the third terminal window, e%ecute the followin# commands H
# cd $CATALINA_HOME/logs
# tail -f localhost_log.YYYY-MM-DD.txt
substitute GGG8118// with the date Cfor e%ample H 200-802811D
"s Tomcat starts up, you can see the messa#es it writes to the 2 lo# files C3tail 8f3 opens the
terminal window in a )ind of console mode, so you can see events as they happenD :f there are
any errors, they will be reflected, sometimes in a very verbose fashion Ta)e note of the errors,
if there are any, and report them on the mailin# list, if you cannot solve it yourself
:f Tomcat started without errors Cor even if it did have errorsD, we can test the servlet with our
browser
/'ec-in# +it' a bro+ser
1 Fpen Betscape or 1oIilla on the local machine
2 7or the UR,, )ey in H httpHAAlocalhostH8080A1y7irstA*elloEorld
- Gou should see a web pa#e that says, very emphatically, <*ello, &ruel Eorld M< :f you
see that, then, con#ratulations M Gour first servlet was successfully deployed M
4.4. *ep"oying 1ava erver 'ages
This operation is actually ?uite strai#htforward *owever, from the amount of email : #et as)in#
me about this, : thou#ht :3d add a section on this topic
/eployin# J;$s is simpler than deployin# web applications Gou will still need to do many of the
steps outlined above 0ut you do not need to define your J;$ file inside the deployment
descriptor, we".xml :f you did not wor) throu#h the previous e%ample, : stron#ly ur#e you to
:t will help in your understandin# " summary of steps you need to do to deploy J;$s is shown
belowH
$eployin# JSs
1 :nstall Tomcat
2 &reate a directory structure for your web application
- "dd a conte%t entry inside server%ml
4 &reate the J;$ file
4 &opy the J;$ file to the appropriate directory Cie #$%&%'I(%)*+M,/we"apps/
0appl!cat!on)name1/D
7or the sa)e of continuity, : am #oin# to assume you did the previous e%ercise To be#in, let us
create a simple J;$ that displays a date and a lin) to the servlet we created earlier The source
code is shown belowH
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello JSP World!</title>
</head>
<body>
<h1>Hello, JSP World!</h1>
<p>
The time now is : <%= new java.util.Date() %>.
</p>
<p>
To see the servlet example <a href="HelloWorld">click here</a>.
</p>
</body>
</html>
</programlisting>
"fter we have created the file, we will save it as inde%(sp and we will deploy it by copyin# it to
the web application directory Recall that the web application directory consists of the followin#
directory structureH
/irectory structure of a new web application
Ee copy the J;$ file Cand subse?uent J;$ filesD into /opt/tomcat/we"apps/M./!rst
directory Bot the classes directory 88 that is for servletsM
"fter we copy the file into the directory, we can test it by simply startin# up Tomcat and enterin#
the followin# UR,H http2//localhost23434/M./!rst/!ndex.jsp
Gou should see a delay, then the pa#e will appear The delay is caused by Tomcat compilin# the
J;$, then returnin# the results to the browser Gou can actually pre8compile J;$s to reduce the
delay by usin# the jspc.sh utility in Tomcat To e%ecute, simply supply the name of the J;$
you wish to compile to the utility li)e so,
# cd $CATALINA_HOME/bin
# ./jspc.sh $CATALINA_HOME/webapps/MyFirst/index.jsp
Chapter ). !dministering Tomcat
There are three administration tools bundled with Tomcat 4 They areH
;erver ;tatus application
Tomcat "dministration Tool
Tomcat 1ana#er
These web applications are bundled with Tomcat by default and can be accessed from the left
sidebar of Tomcat3s default pa#e These tools address the need for simplified administration
which other servlet en#ines, such as Eebsphere or Eeblo#ic, provide
$.1. The Administration Too" We2 Appp"ication
The "dministration Tool web application is the >U: tool for administerin# Tomcat 0efore we can
use it, or any of the >U: tools, we will first need to create a Tomcat administrator account, a
Tomcat mana#er account and two rolesH <admin< and <mana#er<
7or this e%ercise, we will create one user <Tomcat"dmin< who has both mana#er and admin
privile#es
Table )-1. &!ministration 4sers an! Roles
Tomcat "dministrator Role admin This is a built8in role
Tomcat 1ana#er Role mana#er This is a built8in role
Tomcat "dministrator Username Tomcat"dmin
Tomcat "dministrator $assword tcpass
,aunch your favorite editor and add the followin# lines in #reen to
#$%&%'I(%)*+M,/con/tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<role rolename="manager"/>
<role rolename="admin"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="role1" password="tomcat" roles="role1"/>
<user username="TomcatAdmin" password="tcpass" roles="admin,manager"/>
</tomcat-users>
;ave the file, start Tomcat and open a browser Gou should be able to access the "dministartion
Tool web application by clic)in# on the <Tomcat "dministration< lin) on the left sidebar Gou will
be presented with a lo#in screen Just type in your Tomcat "dministrator username and
password, and you should be able to enter the administration tool >U: "n e%ample of this >U:
is shown below The "dministration Tool has collapsible menus on the left &lic) on any of the
icons in the left pane to display information and settin#s in the ri#ht pane /ependin# on the
specifications of your server, the display of settin#s and information in the ri#ht pane can be
very slow M Gou have to be patient and restrain your ur#e to )eep clic)in# if the system seems
unresponsive
Tomcat "dministration Tool
$.2. The 3anager We2 App"ication
Gou can access the 1ana#er Eeb "pplication by clic)in# the <Tomcat 1ana#er< lin) in the left
sidebar of the default Tomcat pa#e This will display a >U: that allows you to view the status of
your installed web applications and even deploy new web applications There is also a lin) to the
<*T1, 1ana#er *elp< which can #ive you more information on usin# the 1ana#er Eeb
"pplication
Tomcat 1ana#er Eeb "pplication
The 1ana#er web application also provides a way to install a new web application, reload it, start
and stop it, and many other functions by merely passin# a UR, 7or e%ample, if we wanted to list
the applications currently deployed in Tomcat, we could open a browser and )ey in
http2//hostname.doma!n.com20port1/mana5er/l!st, and it will return the list that we
re?uire
$.3. tat!s We2 App"ication
7inally, we have the ;tatus web application, which displays the status of the Tomcat server, such
as the memory utiliIation of the J51, the version of J51 bein# run and the number and status of
threads, amon# other parameters This tool is new in Tomcat 4 and can be used to chec) if your
Tomcat server is runnin# low on system resources
;tatus Eeb "pplication
Chapter *. Customi+ing Tomcat
This section e%plores some of the ways you can control the way Tomcat operates This is not
e%haustive 88 Tomcat is e%tremely sophisticated software and there are a lot of thin#s you can
chan#e or twea)
&.1. *isa2"e *irectory Listing
7or fresh Tomcat installations, directory listin# is enabled by default This can be a very useful
debu##in# tool, and if, li)e me, you sometimes for#et what servlets are deployed in a certain
web application, you can #et a complete listin# by simply )eyin# in the web application3s UR,
0ut for production deployments, you may want to turn it off :f nothin# else, it discoura#es users
from po)in# around where they should not There are basically 2 methods of <turnin# off< this
option H
&reate an inde%html file and place it in the web application3s directory
+dit the #lobal web%ml file to turn off the option
The first option is fairly simple, so we shall only e%amine the second option
Fpen the file we".xml which is located inside #$%&%'I(%)*+M,/con/ This is the #lobal
we".xml file, which means that any chan#es here will affect ",, web applications deployed by
that Tomcat instance :f you want more #ranular control, li)e turnin# it off for certain
applications but not for others, you will need to #o with the first option of creatin# !ndex.html
files
,ocate the followin# sectionH
<servlet>
<servlet-name>default</servlet-name>
<servlet-
class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
</sect1>
This is the first section in web%ml The options that concern us are H
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
&han#e Nparam8valueO to false and you turn off directory listin# :t is that simple
&.2. C!stom *e(a!"t 'ages
Tomcat uses the same convention as the "pache Eeb ;erver in that inde%html is the default or
home pa#e of any directory ;ometimes you may want to chan#e that to pa#e1html or maybe a
J;$ pa#e, li)e now'see'this(sp
To do that, simply open the web%ml of your web application, and add the followin# lines H
<welcome-file-list>
<welcome-file>now_see_this.jsp</welcome-file>
<welcome-file>page1.html</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
To chan#e it system8wide, edit the #lobal web%ml in #$%&%'I(%)*+M,/con, and chan#e the
Nwelcome8fileO to point to the file of your choice
&.3. C!stom 4rror 'ages
Unhappy with the default error pa#es that come with Tomcat L Gou can define your own custom
error pa#es in your we".xml file :n the e%ample shown below, we define 2 web pa#es 88
server)error.html and !le)not)ound.html 88 which will be displayed when the server
encounters an error 400 or an error 404 respectively
<error-page>
<error-code>500</error-code>
<location>/server_error.html</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/file_not_found.html</location>
</error-page>
Gou should bear in mind, however, that the order of the ta#s for the web%ml file is very
important :f the order in your web%ml file is incorrect, Tomcat will output errors on startup
Chapter ,. Tomcat Realms
;ometimes, you need to protect your web pa#es andAor web applications, so only re#istered
users can #et access to them To most end8users, they understand this as the lo#in pa#e of the
website To some technical professionals, this is )nown as the authentication facility
" realm is a collection of pa#es, ima#es and applications Ccollectively )nown as <resources<D that
is protected by a lo#in or authentication method 7or Tomcat, the realm mechanism is somewhat
different from how most pro#rammers understand it :nstead of a default servlet that handles
the lo#in, and havin# to set and chec) sessions e%plicitly for every pa#e and servlet, Tomcat has
a container security facility that does it for the pro#rammer &ontainer8mana#ed security
enables the servlet or pa#e author to leave out e%plicit session trac)in# in their code 88 Tomcat
handles the lo#in and session trac)in# for them Ehen a user attempts to access a protected
resource for the first time, he or she will be prompted automatically for hisAher lo#in credentials
There are 4 types of authentication mechanisms provided by Tomcat <out8of8the8bo%<H
0asic "uthentication
7orm8based "uthentication
&ustom "uthentication
/i#est "uthentication
:f you confi#ure for 0asic "uthentication, you will #et prompted with a lo#in dialo# bo% when you
attempt to access a protected resource :f you use 7orm8based authentication, your users will be
redirected to a *T1, pa#e that allows them to lo#in, when they attempt to access a protected
resource &ustom authentication is used when you re?uire additional information from the user
before you allow himAher to lo#in, and /i#est authentication is used when you need an added
level of security usin# hashed passwords
7or a more detailed e%planation of container security, realms and authentication methods,
please refer to ;un3s servlet specifications
5.1. 46ercise Overvie+
The sub(ect of security is actually a lot broader than most people thin) :n addition to
authentication, there is also encryption, authoriIation, auditin#, and a whole host of other
components 7or that reason, :3m not #oin# to #o into the details of security :f you are a system
administrator, you3re probably more interested in how to setup Tomcat for a particular security
scheme than to ar#ue the merits of different methods
: will focus on (ust one particular security setup here Ee will be settin# up a J/0& realm on
Tomcat 4 where the bac)8end database is 7irebird v14, usin# the 1y7irst web application we
developed earlier Ee will be usin# 7orm8based authentication for the lo#in method
Fnce you have wor)ed throu#h this e%ample, : am hopin# that you will also be able to infer the
steps for your own particular setup
5.2. 1*7C ,ea"m
This type of realm involves storin# the credentials of your users Cie their usernames, passwords
and assi#ned rolesD inside a database Tomcat will then need to be confi#ured to use this
database and the J/0& realm option inside the confi#uration files will need to be enabled
;ettin# up a J/0& Realm involves the followin# stepsH
1 :nstall and ;etup The /atabase
2 :nstall the J/0& /river
- ;etup the /atabase Tables
4 Test The J/0& /river and &onnection
4 /eploy and Test the Eeb "pplication
2 $repare the Becessary ,o#in and +rror *T1, 7iles
! +dit Tomcat3s server%ml To +nable J/0& Realm
8 +dit the Eeb "pplication3s web%ml To Re?uire "uthentication
9 ;tart Tomcat and Test
7or this e%ercise, : shall be buildin# on my 7irebird v 14 for ,inu% article Gou can use any
database product you li)e, as lon# as it provides a J/0& driver Cyou could use an F/0& driver
and a J/0&8F/0& driver, but you may want to re8consider this for production deploymentsD The
;=, synta% may also differ, so you should e%pect some differences between my instructions and
your own re?uirements
,.2.1. Install and 'etup the Dataase
To use the J/0& realm, you will need to have a database to store your user credentials :f you
have not already done so, install a database, or use an e%istin# database on your server or
networ) This document will not cover the installation of database products
Gou will also need to ensure that your database can startup and shutdown, and you should be
reasonably familiar with operations on the database you have chosen : will not cover these
aspects here
:f you are a 1icrosoft ;=, ;erver user, : cannot help you : do not use that product, and : hear
that there are all sorts of problems accessin# it with a J/0& driver : personally prefer 7irebird,
because of its compact siIe and because it is free
,.2.2. Install the &D-C Driver
"s : mentioned earlier, you will need a suitable J/0& driver to connect to your database product
: say <suitable< because you could use a J/0&8F/0& brid#e driver, but you would run into
performance problems if your site becomes even moderately loaded "lso, a sin#le database
product may have several different vendors producin# J/0& drivers for their platform "n
e%ample is 1erant, which used to ma)e very hi#h ?uality J/0& and F/0& drivers for a ran#e of
database products :f there are several alternatives, choose a J/0& driver that fits your
performance needs and price ran#e
7or this e%ercise, : am usin# the 7irebird database and the Jay0ird J&"AJ/0& /river for 7irebird
v14 beta- This is a Type 4 J/0& driver, and thou#h it3s in beta, it actually wor)s ?uite well
Gou will need to copy the J/0& driver into #$%&%'I(%)*+M,/common/l!"/ directory :n case
you don3t already )now, the J/0& driver is normally a sin#le (ar or Iip file 7or e%ample, :
believe Fracle3s J/0& driver is called classes.6!p 7or the Jaybird driver, it is !re"!rds7l-
ull.jar Gou will need to refer to your J/0& driver documentation for the filename
,.2.3. 'etting .p The Dataase Tales
There are actually different ways you can setup the tables Gou can even use e%istin# tables of
users, provided you )now how Tomcat does the mappin# : will try to )eep thin#s simple here
and build the re?uisite tables from scratch Gou can see later, with the modifications to Tomcat3s
confi#uration files, how the mappin# method can be inferred
7or this e%ercise, we will create two tables in the database, li)e the ones below, and populate
them with data
Table 1-1. tcusers Table - containin# usernames an! pass+or!s
user9name :varc'ar;2)< not null primary -ey= user9p+! :varc'ar;2)< not null=
taylorsc taylorpass
isabellec isabellepass
daytonr daytonpass
aIleaa aIleapass
Table 1-2. tcroles Table - containin# usernames an! assi#ne! roles
user9name :varc'ar;2)< not null= role9name :varc'ar;20< not null=
taylorsc admin
isabellec admin
user9name :varc'ar;2)< not null= role9name :varc'ar;20< not null=
isabellec mana#er
isabellec tomcat
daytonr mana#er
daytonr tomcat
aIleaa tomcat
primary -ey ;username* rolename<
: will not cover the ;=, statements re?uired :f you need hints, please read my 7irebird article,
which covers the creation of the two tables, but only for 7irebird
Botice that : specified - different roles here H admin, mana#er and tomcat The admin and
mana#er roles are built8in roles for Tomcat, that allow access to the 1ana#er web application
and the Tomcat "dministration Tool Ee can actually test if our J/0& realm wor)s later by
seein# if user <taylorsc< Cwho has the <admin< roleD can lo#in to the "dministration Tool
7or this e%ercise, we will focus on the <tomcat< role, which we will use to determine if a user is
authoriIed to access the resources in the realm
,.2.4. Test The &D-C Driver and Connection
Ee can write a simple J/0& pro#ram to test the connection, to see if we can access the
database
,.2.). Deploy and Test the We !pplication
"t this point, we should deploy and test our web application to verify its functionality before we
put it in a realm and place a lo#in form in front of it
:f you have been followin# alon#, and wor)in# throu#h the e%ercises in this document, you
should already have a *elloEorld servlet deployed in 1y7irst directory, and it should wor) fine
Ee will use the 1y7irst web application to <bootstrap< our J/0& realm
Gou will recall that we created a <tomcat< role when we created and populated the database
tables Ee will use this role later to determine if a user has access to the *elloEorld servlet
,.2.*. (repare the /ecessary 0ogin and 1rror HT20 3iles
7or this e%ercise, we will be usin# 7FR18based
Ee will need 2 *T1, files 88 one for displayin# the lo#in pa#e and one to show the user that he
has )eyed in the wron# password or username
*ere is the lo#in pa#e for this e%erciseH
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login to MyFirst</h1>
<p>
If you have been issued a username and password, key them in here now!
</p>
<form method="POST" action="j_security_check">
Username : <input type="text" size="15" maxlength="25"
name="j_username"><br><br>
Password : <input type="password" size="15" maxlength="25"
name="j_password"><br><br>
<input value="Login" type="submit">&nbsp;&nbsp;&nbsp;&nbsp;<input
value="Clear" type="reset">
</form>
</body>
</html>
Bote the form elements The form action is <$F;T< and the action is <('security'chec)<, the
username field3s name is <('username< and the password field3s is <('password< These elements
1U;T be included for the form to wor)
*ere is the error pa#e for the e%erciseH
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Authentication Error!</title>
</head>
<body>
<h1>Authentication Error!</h1>
<p>
Oops! You either keyed in the wrong username or password.
</p>
<a href="javascript:history.back(1)">Try again ?</a>
</body>
</html>
There are no mandatory elements here The lin) to the previous pa#e is a #ood idea, to allow
the user to return to the lo#in screen
,.2.,. 1dit Tomcat4s server."ml To 1nale &D-C Realm
0y default, the J/0& Realm option is not enabled Gou will need to edit the server.xml file to
enable it ,ocate the followin# section,

<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
debug="0" resourceName="UserDatabase"/>
"nd comment it out, li)e so,
<!--
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
debug="0" resourceName="UserDatabase"/>
-->
Bow, locate the followin# lines in the same file
<!-- Replace the above Realm with one of the following to get a
Realm
stored in a database and accessed via JDBC -->
Gou will need to uncomment one of the J/0& realm definitions below these lines, ta)in# care to
substitute the values for your own database confi#urations values
7or e%ample, : am usin# the 7irebird database, and my J/0& driver and database parameters
are as followsH
Table 1-3. .irebir! !atabase an! J$>/ !river parameters
aramet
er 3ame
server.,ml
e?uivalent
arameter Value Remar-s
/river
Bame
driverBame or#firebirds?l(dbc70/river This value
was provided
by the J/0&
driver
documentatio
n This is
typically the
J/0& driver
name you
would use
when
pro#rammin#
a simple
J/0&
aramet
er 3ame
server.,ml
e?uivalent
arameter Value Remar-s
application
J/0&
&onnectio
n UR,
connectionUR,
(dbcHfirebirds?lHlocalhostA-040HAoptAfirebirdAdbAreal
mdbfdb
To find out
the synta%
and values of
your
connection
UR,, refer to
your J/0&
driver
documentatio
n
/atabase
lo#in
name
connectionBame ;G;/0"
This is the
username
you use to
lo#in to the
database
containin#
the realm
users3
credentials
/atabase
lo#in
password
connection$assw
ord
password
This is the
lo#in user3s
password
User
Table
userTable tcusers
Table
containin# list
of authoriIed
users for the
realm
Bame
&olumn of
User
Table
userBame&ol user'name
The name of
the column
containin#
the list of
users inside
the User
Table
User
$assword
&olumn of
User
Table
user&red&ol user'pwd The name of
the column
containin#
the
respective
aramet
er 3ame
server.,ml
e?uivalent
arameter Value Remar-s
user3s
password in
the User
Table
Role Table userRoleTable tcroles
Table
containin#
the list of
users and
their
respective
roles
Role
Bame
&olumn
roleBame&ol role'name
The name of
the column
containin#
the user3s
assi#ned
roles
Eith this information, we can form the followin# re?uired stanIa for the J/0& realmH
<Realm className="org.apache.catalina.realm.JDBCRealm" debug="0"
driverName="org.firebirdsql.jdbc.FBDriver"

connectionURL="jdbc:firebirdsql:localhost/3050:/opt/firebird/db/realmdb.fdb"
connectionName="sysdba" connectionPassword="password"
userTable="tcusers" userNameCol="user_name"
userCredCol="user_pwd"
userRoleTable="tcroles" roleNameCol="role_name" />
,.2.5. 1dit the We !pplication4s $e."ml To Re6uire !uthentication
Ee need to confi#ure the web application to re?uire authentication as well "t this sta#e, we
determine which resources to protect, who has access, and how we want to protect these
resources That is, we define the directories andAor the files to protect Chtml, (sp, ima#e files or
all filesD, which role has access and which type of authentication we want to use C7orm8based,
0asic, &ustom or /i#estD
7or this e%ercise, this is what we want to protectH
+verythin# in the 1y7irst application, that is, all *T1, files, ima#e files, J;$ files,
servlets, te%t files, everythin#M
"ny and all access methods, that is, *TT$ >+T, $UT, $F;T, /+,+T+, will #et the lo#in
prompt
Eho can access itH
Fnly users with the 3tomcat3 role are allowed to access the 1y7irst web application
*ow we want to protect the resourcesH
Ee will use 7orm8based authentication
The lo#in pa#e is lo5!n.html
The error pa#e, if the user )eys in the wron# username or password is autherr.html
Ee also need to define the roles that will have access 7or this e%ercise, we only want users with
the 3tomcat3 role to have access
To e%press these re?uirements, we )ey in the stanIa below into the web application3s we".xml
file, after the Nservlet8mappin#O section and before the terminatin# NAweb8appO ta#
<security-constraint>
<web-resource-collection>
<web-resource-name>MyFirst</web-resource-name>
<description> accessible by authenticated users of the
tomcat role</description>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
</web-resource-collection>
<auth-constraint>
<description>These roles are allowed access</description>
<role-name>tomcat</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>MyFirst Protected Area</realm-name>
<form-login-config>
<form-login-page>/login.html</form-login-page>
<form-error-page>/autherr.html</form-error-page>
</form-login-config>
</login-config>
<security-role>
<description>Only 'tomcat' role is allowed to access this web
application</description>
<role-name>tomcat</role-name>
</security-role>
T'e or!er of t'e sections is important@ (f you #et errors on Tomcat startup* it may be
!ue to t'e or!erin# of your sections. .or e,ample* t'e Asecurity-constraintB section
can "3CD come after t'e Aservlet-mappin#B section. .or more !etails on t'e proper
or!er* rea! t'e Servlet Specifications !ocument.
Bow, we are finally ready to test our J/0& realm M
,.2.7. 'tart Tomcat and Test
5erify that the lo#inhtml and autherrhtml files are in the 1y7irst web application directory Gour
Tomcat en#ine should be stopped at this time ;tart Tomcat and open a browser Try to access
the *elloEorld servlet Gou should #et redirected to the lo#in pa#e Csee belowD
.ey in the username and password of a user who does PnotP have the tomcat role Gou should
#et the error pa#e
Be%t, )ey in the username and password of a user who has the 3tomcat3 role, and clic) the ,o#in
button Gou should then see the familiar *elloEorld servlet pa#e
Chapter 5. Integrating Tomcat ) and !pache 2
There are two ways Cthat : )now ofD to inte#rate Tomcat with "pache 2H
"pache can be confi#ured to pro%y re?uests sent to Tomcat
"pache can pass re?uests to Tomcat via connectors such as mod'()2
8.1. #sing mod9:;2
: don3t )now if mod'() still wor)s for Tomcat 4 : do )now that mod'webapp development
seems to have lapsed, so : shall concentrate on mod'()2 inte#ration :f you )now of other
methods of inte#ratin# Tomcat and "pache, please let me )now M
5.1.1. 8etting the mod9:;2 connector
T'e Ja-arta #roup release! version 2.0.4 of t'e mo!9E-2 connector on 20 Farc' 2004.
T'is release inclu!es source pac-a#es an! RF pac-a#es for .e!ora /ore 1* Suse G an!
Suse SC7S 2. ( +ill only be coverin# t'e source pac-a#e compilation on .e!ora /ore for
t'is !ocument.
>inary RF pac-a#es are available for .e!ora /ore 1* S4S7 G.0 an! S4S7 SC7S at t'e
Ja-arta !o+nloa! site or mirrors. (Hm not #oin# to be coverin# t'e RF pac-a#es in
t'is !ocument.
T'is release cleans up a lot of t'e bu#s an! annoyances t'at use! to pla#ue users of
t'e previous release. (tHs actually ?uite #oo! -- but t'en* Henri 6omeI !oes #oo!
+or- @
The source pac)a#e cannot be accessed directly from the lin)s on the Ja)arta site Cstran#ely
enou#hMD "nd because the Ja)arta site will redirect you to the nearest mirror, the location of the
source pac)a#e may vary from site to site 1y local mirror has the source tarball in this locationH
httpHAAapacheosseInetsolsor#A(a)artaAtomcat8connectorsA()2AsourceA
:f you clic)ed on the lin) for the J.2 0inary Releases on the Ja)arta site, you will need to clic) on
<$arent /irectory<, then <source< directory CBoteH your location may varyMD
This document has been updated for H (a)arta8tomcat8connectors8()282048srctar#I
5.1.2. 'erver 1nvironment and 'ystem Re6uirements
0ecause many of the comple%ities of settin# up mod'()2 come from the environment itself, such
as the layout of the "pache 2 files, or the availability of libraries, : will need to define my
environment for this e%ercise :f your environment differs, please note that you may have to
ma)e some chan#es to the instructions here
Table 2-1. Server /omponents
Cinu,
$istribution
Java Virtual Fac'ine
&pac'e
version
Tomcat
version
mo!9E-2
version
7edora &ore 1
:01 Java 2 ;/. v141
;R1
2048 4018 204
The followin# libraries were also installedH
apr8util809482
apr809482
apr8util8devel809482
apr8devel809482
automa)e81!881
autoconf824!8-
m48141814
libtool8libs81488
libtool81488
pcre84481
pcre8devel84481
: believe that they are all re?uired for the compilation of the J.2 source pac)a#es :f you #et a
AlibAcpp sanity chec) failure when runnin# the confi#ure script, chec) that you have the followin#
installedH
libstdcQQ8devel8--281
#cc8cQQ8--281
7or all the above items, : am not sure if the version matters, but these versions wor)ed for me
5.1.3. 1"ercise <vervie$
0uildin# the mod'()2 binary and inte#ratin# Tomcat and "pache is easier if we define a set of
steps
(nte#ratin# &pac'e an! Tomcat +it' J%2
1 :nstall Tomcat and verify that it is wor)in# properly
2 :nstall "pache 2 and verify that it is wor)in# properly
- ;hutdown both Tomcat and "pache
4 /ownload, build and install the mod'()2 source files
4 +dit the confi#uration files httpd.con, jk2.propert!es, workers2.propert!es
and server.xml
2 ;tart Tomcat
! ;tart "pache
8 5erify that everythin# wor)s
5.1.4. -uilding mod9:;2
8.1.4.1. Install Tomcat and verify that it is working properly
:nstall Tomcat and verify that all the servlet and J;$ e%amples wor) properly :f you wor)ed
throu#h the earlier sections, you should already have a wor)in# Tomcat setup
8.1.4.2. Install Apache 2 and verify that it is working properly
: am usin# the R$1 pac)a#es for 7edora &ore for this e%ercise : will not be coverin# the
installation of the source tarball or other R$1 pac)a#es :n any case, there are plenty of
resources and documentation available for this tas)
5erify that "pache 2 is wor)in# by startin# and stoppin# the http daemon and try to access web
pa#es on it
8.1.4.3. Shtdown !oth Tomcat and Apache
:f you are ready to build the mod'()2 binary from the source pac)a#e, you should shutdown
both Tomcat and "pache Ee will start them up momentarily, after we have finished the ne%t
step
8.1.4.4. "ownload# compile and install the mod$%k2 sorce files
:f you have already downloaded the pac)a#e, navi#ate to the download directory and unpac) the
tarball
[chongym@localhost mod_jk2]$ tar -zxvf jakarta-tomcat-connectors-jk2-
2.0.4-src.tar.gz
Bow, you will need to navi#ate to the build directory
[chongym@localhost mod_jk2]$ cd jakarta-tomcat-connectors-jk2-2.0.4-
src/jk/native2/
[chongym@localhost native2]$ ls
aclocal.m4 B8I'9.txt common I(:&%''.txt scr!pts
apr "u!ld.xml con!5ure jn! server
autom4te.cache $*%(;,:.html con!5ure.!n Make!le.!n :&%&8:.txt
"u!ldcon.sh $*%(;,:.txt !nclude <,%9M,.txt tomcat
7or the ne%t few steps, you will need to be root user to build the J.2 binary
[chongym@localhost native2]$ su root
=assword2
[root@localhost native2]# ./configure --with-apxs2=/usr/sbin/apxs \
--with-tomcat-41=/opt/tomcat \
--with-apr-lib=/usr/lib \
--with-java-home=/opt/IBMJava2-141 \
--with-jni
Ehen you e%ecute <confi#ure<, the switches that you will use will probably differ from mine if
you are not usin# 7edora &ore 1, or if you built your own "pache binaries These are my
settin#sH
&JS pat'5 /usr/s"!n/apxs
Tomcat pat'5 /opt/IBMJava2-141 8 yes, : am usin# the :01 Java 2 ;/.
J&V&9H"F75 : have enabled the JB: switch EhyL :3m not really sure Just that every other
documentation out there says so
:f the configure completed successfully, you should see these lines at the end of the processH
con!5.status2 creat!n5 server/apache1>/Make!le
con!5.status2 creat!n5 server/apache1>/Make!le.apxs
con!5.status2 creat!n5 server/apache2/Make!le
con!5.status2 creat!n5 server/apache2/Make!le.apxs
con!5.status2 creat!n5 ../"u!ld.propert!es
con!5.status2 creat!n5 scr!pts/"u!ld/un!x/dumm.
con!5.status2 execut!n5 dep!les commands
Bow, you can e%ecute the make command,
[root@localhost native2]# make
:f it completes successfully, you should see somethin# li)e thisH
l!"tool2 !nstall2 warn!n52 remem"er to run ?l!"tool --!n!sh
/usr/l!"/httpd/modules@
/"!n/cp ../../../"u!ld/jk2/apache2//usr/l!"/httpd/modules/l!"jkjn!.so
../../../"u!ld/jk2/apache2/l!"jkjn!.so
make0112 'eav!n5 d!rector.
?/home/chon5.m/downloads/jk2/jakarta-tomcat-connectors-jk2-2.4.4-
src/jk/nat!ve2/server/apache2@
Ee don3t really need to run 3libtool3, but for the sa)e of completeness, let3s e%ecute it as
su##ested by the messa#es above
0rootAlocalhost nat!ve21B l!"tool --!n!sh
----------------------------------------------------------------------
'!"rar!es have "een !nstalled !n2
I .ou ever happen to want to l!nk a5a!nst !nstalled l!"rar!es
!n a 5!ven d!rector.C 'IB9I<C .ou must e!ther use l!"toolC and
spec!. the ull pathname o the l!"rar.C or use the ?-''IB9I<@
la5 dur!n5 l!nk!n5 and do at least one o the ollow!n52
- add 'IB9I< to the ?'9)'IB<%<D)=%&*@ env!ronment var!a"le
dur!n5 execut!on
- add 'IB9I< to the ?'9)<8()=%&*@ env!ronment var!a"le
dur!n5 l!nk!n5
- use the ?--lC--rpath --lC'IB9I<@ l!nker la5
- have .our s.stem adm!n!strator add 'IB9I< to ?/etc/ld.so.con@
:ee an. operat!n5 s.stem documentat!on a"out shared l!"rar!es or
more !normat!onC such as the ldE1F and ld.soE3F manual pa5es.
----------------------------------------------------------------------
Bow, we run the "$6; tool a#ainst the mod'()2 shared library
[root@localhost native2]# cd ../build/jk2/apache2
[root@localhost apache2]# /usr/sbin/apxs -n jk2 -i mod_jk2.so
:f the apxs command e%ecuted successfully, you should see thisH
/usr/l!"/httpd/"u!ld/!nstdso.sh :*)'IB&++'G@/"!n/sh
/usr/l!"/apr/"u!ld/l!"tool@
mod)jk2.so /usr/l!"/httpd/modules
/"!n/sh /usr/l!"/apr/"u!ld/l!"tool --modeG!nstall cp mod)jk2.so
/usr/l!"/httpd/modules/
cp mod)jk2.so /usr/l!"/httpd/modules/mod)jk2.so
-arn!n5H dlname not ound !n /usr/l!"/httpd/modules/mod)jk2.so.
%ssum!n5 !nstall!n5 a .so rather than a l!"tool arch!ve.
chmod I55 /usr/l!"/httpd/modules/mod)jk2.so
"t this point : would li)e to e%plain a little about what ap%s is and what it does "ccordin# to the
"pache documentation, "$6; is the "$ache e6ten;ion Tool :t3s stated purpose is for buildin#
and installin# e%tension modules to "pache by buildin# /ynamic ;hared Fb(ect C/;FD files from
source files Ehat this means is that : can add e%tensions to the "pache web server without
needin# to re8compile it
:f the apxs command e%ecuted successfully, you should find both mod'()2so and lib()(niso
inside the current directory, which isH your_download_directory/jakarta-tomcat-
connectors-jk2-2.4.4-src/jk/"u!ld/jk2/apache2
Gou should then copy those two files into /usr/l!"/httpd/modules/ Bote that you will have
to rename l!"jkjn!.so to jkjn!.so
[root@localhost apache2]# cp libjkjni.so /usr/lib/httpd/modules/jkjni.so
[root@localhost apache2]# cp mod_jk2.so /usr/lib/httpd/modules/mod_jk2.so
5.1.). 1dit Con#iguration 3iles httpd.con#% :;2.properties%
$or;ers2.properties and server."ml.
"t this point, you have to ma)e a choice about the type of connection channel you want to use
to connect "pache with Tomcat There are 4 types of connections
&hannel soc)ets
UB:6 soc)ets
"$R soc)ets
JB: channels
5.1.*. Con#iguring #or ./I= soc;ets
: will only be coverin# the confi#uration for UB:6 soc)ets in this document
8.1.&.1. 'nvironment (aria!les
Gou will need to set one environment variable inside catal!na.sh ,ocate the followin# code
bloc) inside the scriptH
# Get standard environment variables
PRGDIR=`dirname "$PRG"`
CATALINA_HOME=`cd "$PRGDIR/.." ; pwd`
if [ -r "$CATALINA_HOME"/bin/setenv.sh ]; then
. "$CATALINA_HOME"/bin/setenv.sh
fi
"ppend below it the followin# lines and save the file
# Set serverRoot
serverRoot=/etc/httpd2
export serverRoot
Be%t, you will need to edit your confi#uration files Try not to use the default files that come with
your source download The default files have a lot of options inside them, and may not wor)
Dou F4ST ensure t'at &pac'e an! Tomcat 'ave been s'ut!o+n before e!itin# t'ese
files because t'ey may be over-+ritten +'en eit'er !aemon is starte!.
There are - files you will need to edit and one file you will need to chec)H
Table 2-2. /onfi#uration .iles .or 43(J soc-ets
.ilename Cocation &ction To Ta-e
httpd.con /etc/httpd/con/
+dit this file
jk2.propert!es /opt/tomcat/con
&reate this file
workers2.propert!es /etc/httpd/con
&reate this file
server.xml /opt/tomcat/con
&hec) this file
8.1.&.2. httpd.conf
Gou will need to ma)e "pache2 aware of the Tomcat connector "dd the followin# lines into
httpdconf, at the end of the ,oad1odule bloc)H
LoadModule jk2_module /usr/lib/httpd/mod_jk2.so
8.1.&.3. %k2.properties
0ac)up the e%istin# ()2properties file in this directory, then create a new ()2properties
implementin# UB:6 soc)ets, as shown below H
# jk2.properties
# Configured for channel UNIX
# Set the desired handler list
handler.list=apr,request,channelUnix
# UNIX Domain socket location
channelUnix.file=/opt/tomcat/work/jk2.socket
# Dynamic Library
serverRoot=/etc/httpd
apr.NativeSo=/usr/lib/httpd/modules/jkjni.so
8.1.&.4. workers2.properties
" sample wor)ers2properties implementin# UB:6 soc)ets is shown below H
# workers2.properties
# Shared memory handling. Needs to be set.
[shm]
info=Scoreboard. Required for reconfiguration and status with multiprocess
serve
rs
file=/opt/tomcat/logs/jk2.shm
size=1048576
debug=0
disabled=0
# UNIX domain socket
[channel.un:/opt/tomcat/work/jk2.socket]
tomcatId=localhost:8009
debug=0
# define the worker
[ajp13:/opt/tomcat/work/jk2.socket]
channel=channel.un:/opt/tomcat/work/jk2.socket
# Announce a "status" worker
[status:status]
info=Status worker. Displays runtime information.
[uri:/jkstatus/*]
group=status:status
# Uri mapping
[uri:/examples/*]
# Uri mapping for MyFirst
[uri:/MyFirst/*]
8.1.&.). server.*ml
Gou will need to ensure that the followin# code bloc) in server.xml is uncommented 0y
default, it already is, but if you have been tin)erin# with your setup, you would probably want to
chec), (ust to be sure
<!-- Define a Coyote/JK2 AJP 1.3 Connector on port 8009 -->
<Connector port="8009"
enableLookups="false" redirectPort="8443" debug="0"
protocol="AJP/1.3" />
8.1.&.&. +heck for %k2.shm
+arlier, you defined a file jk2.shm in workers2.propert!es This file should be automatically
created when Tomcat is run ;tart Tomcat now, if you have not already done so and verify that
the file is created and is writeable by the UB:6 user that the Tomcat daemon runs under 7or
this e%ercise, that user would be 3tomcat3
8.1.&.,. %k2.socket -ermissions
This file is crucial for communications between "pache and Tomcat, and therefore must be
readable and writeable by both the "pache user and the Tomcat user This file is also
automatically #enerated when Tomcat starts up This file has read and write permissions for user
and #roup This means that you need to put both the "pache user and the Tomcat user in the
same #roup 7or this e%ercise, we will put 7edora3s "pache user, called 3apache3 inside the
Tomcat #roup, called 3tomcat3H
[root@localhost logs]# usermod -G apache,tomcat apache
8.1.&.8. "eploying .e! Applications
7or every web application, we must supply a Uri mappin# 7or e%ample, for our 1y7irst web
application, we simply append to our wor)ers2properties the followin#H
[uri:/MyFirst/*]
Bow, you are ready to test ;ince both "pache and Tomcat are stopped, we will need to start
them up
5.1.,. 'tart Tomcat
7or the confi#urations defined here, the startup processes for "pache 2 and Tomcat are <de8
coupled<, that is, when you start "pache, Tomcat does not automatically start up as well This is
important for troubleshootin# "t this point we want to )now if the basic confi#uration wor)s at
all
The startup se?uence for our confi#uration is H you start Tomcat first, then "pache Fn startup,
Tomcat reads its own confi#uration files such as server.xml and we".xml first, then reads
jk2.propert!es, from which it e%tracts some important information H
Ehich handlers to use
The port it listens on
The hostname or :$ address it e%pects the connection from "pache to ori#inate from
To chec) on the pro#ress of the startup, do this as tomcat user,
[tomcat@localhost tomcat]$ tail -f $CATALINA_HOME/logs/catalina.out
5.1.5. 'tart !pache
Fnce Tomcat has started up, you can start "pache :t would be a #ood idea to view the "pache
lo#s for details andAor errors, at this point
To do this, as root, e%ecute the followin# command H
[root@localhost run]# tail -f /var/httpd2/logs/error_log
5.1.7. >eri#y that everything $or;s
Fpen a browser and )ey in the UR, 7or our web application 31y7irst3, the UR, to )ey in for the
*elloEorld servlet would be http2//localhost/M./!rst/*ello-orld :f you #et an error,
chec) to see if you followed the instructions closely "nother thin# to chec) are the error lo#s
:f everythin# wor)s, con#ratulations M Gou have successfully inte#rated "pache and Tomcat M
8.2. ,everse 'ro6y +ith Apache
:f you don3t want to mess with the comple%ities of mod'()2, but you need to put "pache in front
of Tomcat, there is an alternative, and that is to setup reverse pro%yin# in "pache
"ccordin# to the "pacheEee) website, <a reverse pro%y is a #ateway for servers, and enables
one web server to provide content from another transparently< This can sometimes result in
better response times, because of cachin#, and also better security for servers behind a firewall
Eith all these advanta#es, why would one want to use mod'()2, you may as) L Eell, that3s a
?uestion : really am not ?ualified to answer The only drawbac) that : )now of, for pro%yin#, is
that your web application sees only one client, and that is the "pache server This ma)es it
difficult for auditin# and forensics 88 should the need arise There are ways to resolve this
pro#rammatically, of course, but : will not be coverin# that here
5.2.1. 'ystem Re6uirements
These instructions cover H
7edora &ore 2
httpd8204984
:f you choose this method of inte#ration, be aware that you may need to )now your server3s
/B; name and interfaces This is because : will be usin# the name8based virtual hostin# method
on "pache 0e aware of this difficulty, especially if you do not come from a networ)in#
bac)#round
5.2.2. 1"ercise <vervie$
This tour of reverse pro%yin# assumes the followin#H
: will be settin# up reverse pro%y for a host called www.v!ra5o.com.s5 There is, of
course no such host or domain on the public :nternet Gou can substitute your favorite
domain and hostname for this name
Tomcat and "pache e%ist on the same machine :f your deployment has "pache and
Tomcat on separate machines, you will need to refer to the 5irtual*ost stanIa and locate
where it defines Tomcat3s server hostname in the $ro%y$ass and $ro%y$assReverse
directives and ma)e the appropriate chan#es
5.2.3. 1dit Tomcat4s server.xml
Gou will need to locate the followin# stanIa and uncomment it
<!-- Define a Proxied HTTP/1.1 Connector on port 8082 -->
<!-- See proxy documentation for more information about using this.
-->
<!--
<Connector port="8082"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false"
acceptCount="100" debug="0" connectionTimeout="20000"
proxyPort="80" disableUploadTimeout="true" />
-->
Bote that in the stanIa above, we are usin# port 8082 as the reverse pro%y port for Tomcat Gou
will need to remember this when we edit "pache3s confi#uration
5.2.4. 1dit !pache4s httpd.conf
Gou need to ensure that the followin# pro%y directives inside httpd.con are uncommented
Cwhich they normally are by defaultD
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
There are actually 2 ways that you can add reverse pro%yin# to "pache The first involves usin#
the N,ocationO directive while the second involves settin# up a 5irtual *ost definition : will be
coverin# the second option
;uppose that we have a virtual host www.v!ra5o.com.s5, and its :$ address is
1J2.1K3.4.244, and we want to use name8based virtual hostin#
Ee add the followin# line into httpd.conH
NameVirtualHost 192.168.0.200:80
Then we setup the virtual host stanIa li)e soH
<VirtualHost 192.168.0.200:80>
ServerName www.virago.com.sg
DocumentRoot /var/www/html
DirectoryIndex index.html index.shtml
</VirtualHost>
Ee only need to add a couple of lines to enable reverse pro%yin# :3ll (ust show the full virtual
host stanIa with the two lines included belowH
<VirtualHost 192.168.0.200:80>
ServerName www.virago.com.sg
DocumentRoot /var/www/html
DirectoryIndex index.html index.shtml
ProxyPass /MyFirst http://www.virago.com.sg:8082/MyFirst
ProxyPassReverse /MyFirst http://www.virago.com.sg:8082/MyFirst
</VirtualHost>
0efore we continue, let me e%plain the setup aboveH
: am assumin# that both Tomcat and "pache are installed on the same bo% This is why
the =rox.=ass and =rox.=ass<everse refer to http2//www.v!ra5o.com.s523432
which is the UR, to reach Tomcat :n your deployment, that is probably not #oin# to be
the case, so you need to replace that UR, with the UR, for your Tomcat server
7or the =rox.=ass and =rox.=ass<everse directives, note that : defined two
<ar#uments<H the first <ar#ument<, /M./!rst refers to the UR, that a user )eys in,
while the second <ar#ument< refers to where that UR, maps to ;o, if a user opens a
browser and )eys in http2//www.v!ra5o.com.s5/M./!rst, that re?uest #ets sent to
Tomcat server UR, http2//www.v!ra5o.com.s523432/M./!rst via "pache3s pro%y
Bote that if your server needs to be accessible from the public :nternet, there may be a few
thin#s you need to chan#e in your /B; entries, especially if you wish to e%pose the Tomcat
server to the :nternet :t is perfectly all ri#ht to hide Tomcat behind a firewall, while the "pache
server sits on the /1R, but you need to ensure that the "pache server can resolve Tomcat3s
address and reach it
This is not a comprehensive e%planation of virtual hostin# :f you re?uire more clarification, or if
you encounter problems with this setup, or if this setup is not what you want, please refer to the
"pache documentation on virtual hostin# or search for it on the :nternet
5.2.). Testing !pache4s Reverse (ro"y
To test this setup, simply start your Tomcat and "pache servers and open a browser Type in the
UR, http2//www.v!ra5o.com.s5/M./!rst/*ello-orld and you should see the Tomcat
pa#e come up
" lot of the time, the reason for most difficulties is that "pache cannot reach the Tomcat server,
either because of firewall rules that bloc) access on the pro%y port Cie 8082 is Tomcat3s default
&hec) what your pro%y port is in server.xmlD, or because of name resolution problems To see
if this is the case, you need to loo) inside Tomcat3s lo#s :f you are usin# a clean system, with
no special lo##in# defined, the access lo# is localhost)lo5.Esome)dateF.txt &hec) if any
re?uests are comin# into Tomcat :f none are, then you )now you have a networ) problem
;pea) to your networ) administrator to resolve it
Chapter 7. Re#erences and .se#ul 0in;s
"re you usin# a different Java2 ;/., or a different "pache version L Fr maybe your deployment
is different 88 you need virtual hostin# instead of the relatively strai#htforward method of
deployment shown here Fr maybe you (ust thin) that my writin# suc)s
Eell, there is an alternative to (ust flamin# meM There are a lot of other people who have
volunteered their time and effort, producin# ?uality documentation for Tomcat ,isted below are
some lin)s that you may find useful "lso, if you )now of any #ood sites, or if you want me to
lin) to your site, please email meM
7irst, some lin)s to pa#es that e%plain other deployment methods or environmentsH
Table G-1. References "n Various Tomcat $eployments
/onfi#uration $escription
Tomcat 412! Q "pache 204! Q
mod'() CR*9D
John Turner3s e%cellent *FETF for usin# mod'() instead
of mod'()2 to connect Tomcat and "pache 2 Gou can find
it here This is for Red *at ,inu% 9
Tomcat 4118 Q "pache 204- Q
mod'() CEindows 6$A2000D
"nother e%cellent *FETF by John Turner, this time for the
Eindows platform Gou can find it here
Eeb ;ervices with Tomcat Q "pache
Q ;truts Q $ost#re;=, Q Fpen;;,
Q J/0&
Fscar &arrillo3s e%cellent write8up on this dauntin#
confi#uration Gou can find it here, and is well worth the
effort wor)in# throu#h it
Tomcat 40%A41% 5irtual *ostin#
>alatea3s 7lash>uides "lways useful Gou can find the
details here There are other flash#uides which you can
find here
Tomcat 41% Q "pache 2 Q
mod'()2
Ja)arta site3s mini8*FETF for virtual hostin#
&oncise Tomcat 41% Q ;un Java 2
;/. Q "pache 2
1ichael &ardon has written a more concise article on this,
compared to my verbose one :f you3re in a hurry, he is
your man Read it here
;ome interestin# articles and reference materials on TomcatH
Java ;ervlet ;pecifications 24
Tomcat 4 is an implementation of version 24 of the Java ;ervlet ;pecifications ;ome
?uestions are best answered by #oin# bac) to this document
FnJavacom
The F3Reilly site has some really useful articles on Java and Tomcat There3s an article
on the Top Ten Tomcat &onfi#uration Tips and one on new features in Tomcat 4, Ehat3s
Bew in Tomcat 4 Gou should chec) the site periodically for new articles
The Tomcat 0oo) $ro(ect
This is a ;ourcefor#e pro(ect that seems to have lapsed ;ome useful information here,
nonetheless and the writin# is a lot better than mine in some places $lus, there are
translations M
Ja)arta ;ite3s Tomcat 7"=
This 7"= seems to be compiled from truly fre?uently as)ed ?uestions on the Tomcat
mailin# list
!ppendi" !. mod9:;2 4?4 1rror (rolem @With Help 3rom Trevor
-utlerA
T'is solution +as !evelope! +it' 'elp from Trevor >utler.
: have found that for certain versions of ,inu%, the deployment method : described for "pache8
Tomcat inte#ration with mod'()2 may not wor) ;pecifically, entries in the confi#uration file
workers2.propert!es that map web application conte%ts on Tomcat may not wor) : have
noticed this anomaly when the components described below are usedH
Table &-1. otentially roblematic /ombination "f /omponents
,inu% distribution 1andra)e 92
"pache version 1andra)e3s "dvanced +%tranet ;erver
mod'()2 J$ac)a#e mod'()2 R$1 pac)a#e
A.1. 'ro2"em *escription
Gou #et <404 +rrors<, even thou#h you followed all the instructions in this document Ehen you
loo) inside the "pache error lo#s, you find that re?uests are not #ettin# passed to Tomcat, and
"pache is instead tryin# to find the re?uested documents under its own DocumentRoot
This problem loo)s li)e there is somethin# wron# with mod'()2 0ut if you try to access the
status pa#e, that is, usin# a browser to #o to httpHAAdomaincomA()statusA, you #et a full normal
listin# of the web applications currently deployed on Tomcat
"nother symptom of this problem is, you find that you need to e%plicitly declare each and every
servlet and J;$ file deployed in every conte%t, in order to ma)e them accessible, and to avoid
the 404 errors
A.2. Why does this happen?
The 404 errors are occurrin# because "pache seems to be i#norin# wildcard specifications of
conte%ts in wor)ers2properties 7or e%ample, if, in workers2.propert!es, you specified a
conte%t called M./!rst this wayH
[uri:/MyFirst/*]
Gou would find that tryin# to call the *elloEorld servlet is futile, and would #ive you a 404 error
<$a#e not found< Gou could even try to call the !ndex.jsp file specified in my document, or
any other pa#e, and it would return you a 404 error
Fne solution around this is to specify each and every resource in the web application conte%t
7or e%ample, for the *elloEorld servlet and !ndex.jsp, you would need 2 UR: mappin#s in
workers2.propert!es, not (ust one
[uri:/MyFirst/HelloWorld]
[uri:/MyFirst/index.jsp]
:f you have a lot of servlets, J;$s, *T1, pa#es, etc, this approach may be unfeasible ;o, how
do you use wildcards in this situationL
A.3. A o"!tion
"s it turns out, specifyin# your conte%t in workers2.propert!es is not the only way to tell
"pache to route web application conte%t re?uests to Tomcat The web application conte%t can be
specified within "pache3s own confi#uration file :f you are usin# 1andra)e3s "dvanced +%tranet
;erver, that file would be /etc/httpd2/con/httpd2.con :f you use this approach, you
may need to delete the UR: conte%ts in workers2.propert!es
: will use the e%ample developed earlier in this tutorial ;uppose : have a *elloEorld servlet and
an !ndex.jsp file in the conte%t called M./!rst : will assume that you either built the
mod'()2so and ()(niso libraries successfully, or that you downloaded and have already
successfully installed the mod'()2 R$1 pac)a#e from J$ac)a#eor#
To specify the 1y7irst web application conte%t to "pache, we append the followin# lines to the
bottom of /etc/httpd2/con/httpd2.con H
# URI definitions
<Location "/MyFirst/*">
JkUriSet worker ajp13
</Location>
:n some cases, you may need to enclose the conte%t definitions inside IfModule, li)e soH
<IfModule mod_jk2.c>
# URI definitions
<Location "/MyFirst/*">
JkUriSet worker ajp13
</Location>
</IfModule>
Botice that this specifies a wildcard This means that a browser that re?uests anythin# from
http2//doma!n.com/M./!rst/, will automatically have his re?uest routed by "pache to
Tomcat
This solved the problem for me :f you )now of anythin# else that may help, or if you would li)e
to e%pand on my solution, feel free to email me M
!ppendi" -. !out the changes in $e application deployment
section
Fne of the thin#s : really en(oy about Fpen ;ource software is that you can sometimes #et
useful insi#hts from people smarter and more e%perienced than yourself : had an interestin#
discussion with Josh Rehman on the relative merits of deployin# web applications usin# the
server.xml method or usin# the conte%t descriptor method
Josh3s position is that the conte%t descriptor method should become the canonical method for
web application deployment for many reasonsH the unreliability of server.xml edits
propa#atin# throu#h the server, and the difficulty of removin# those conte%ts that are already
deployed
: had not considered that position before, probably because : do not run Tomcat in a hi#h
volume, mission8critical environment Thin#s are different in the little corner of "sia where : stay
and wor) The traffic is much lower and you can pretty much reboot the server anytime you
wish ;o brin#in# down the Tomcat server process to add, modify or delete a conte%t is feasible
:f, however, you have responsibilities for a lar#e deployment of Tomcat servers, or (ust a Tomcat
server runnin# in a hi#h volume environment, the #ame chan#es fundamentally Gou will need
somethin# that allows for <on8the8fly< chan#es, and more importantly, you need a clear
separation between server confi#uration parameters shared by all applications, and
confi#urations for each individual web application "lthou#h there are merits in )eepin# all
confi#uration in one place, when you are pressed for time, you don3t want to wade throu#h an
ultra8lon# confi#uration file to #et at the parts you want to chan#e or delete : learned that
painful lesson when addin# a &/8RE drive to a runnin# web server recently
;o, than)s #o out to Josh for his su##estions : have chan#ed the section on web application
deployment, and : must say that overall, it all ma)es more sense now
!ppendi" C. -uilding mod9:;2 on Red Hat 1nterprise 0inu" 3 BRH10C
@Contriuted y !ndre$ CluteA
T'is solution +as contribute! by &n!re+ /lute. T'e actual te,t of t'e email 'as
been a!apte! for instructions.
These steps apply to a stoc) R*+, install and mod'()2 version 204 $lease refer to the chapter
on <:nte#ratin# Tomcat 4 and "pache 2 for additional information on #ettin# mod'()2 and
e%pandin# the tar archive
>uil!in# mo!9E-2
1. "s root, run configure with the followin# optionsH
[root@localhost native2]# ./configure --with-apxs2=/usr/sbin/apxs \
> --with-apr-lib=/usr/lib \
> --with-tomcat-41=$CATALINA_HOME \
> --with-java-home=$JAVA_HOME \
> --with-jni
2. "fter confi#ure e%ecutes successfully, you will need to to modify the 1a)efile inside
./server/apache2 ,ocate the followin# bloc)H
ifdef APR_LIBDIR_LA
JK_LDFLAGS=-L${APACHE2_LIBDIR} -lcrypt
else
JK_LDFLAGS=-lcrypt ${APR_LIBS}
endif
"nd chan#e it to thisH
ifdef APR_LIBDIR_LA
JK_LDFLAGS=-L${APACHE2_LIBDIR} -lcrypt
else
JK_LDFLAGS=-lcrypt ${APR_LIBS} -laprutil-0
endif
Bote the addition of -laprutil-0 in the second line
3. Gou can now run make as root user
4. "fter ma)e completes, chec) that the file l!"jkjn!.so is built with the necessary
shared libraries To do this, run ldd a#ainst that file Gou should see somethin# li)e thisH
[root@localhost modules]# ldd libjkjni.so
l!"cr.pt.so.1 GL /l!"/l!"cr.pt.so.1 E4x"I5Je444F
l!"apr-4.so.4 GL /usr/l!"/l!"apr-4.so.4 E4x"I5I444F
l!"aprut!l-4.so.4 GL /usr/l!"/l!"aprut!l-4.so.4 E4x"I5Ka444F
l!"c.so.K GL /l!"/tls/l!"c.so.K E4x"I4>1444F
l!"rt.so.1 GL /l!"/tls/l!"rt.so.1 E4x"I41d444F
l!"m.so.K GL /l!"/tls/l!"m.so.K E4x"I>"444F
l!"nsl.so.1 GL /l!"/l!"nsl.so.1 E4x"I>eK444F
l!"dl.so.2 GL /l!"/l!"dl.so.2 E4x"I>e>444F
l!"pthread.so.4 GL /l!"/tls/l!"pthread.so.4 E4x"I>d>444F
l!"d"-4.1.so GL /l!"/l!"d"-4.1.so E4x"I>14444F
l!"expat.so.4 GL /usr/l!"/l!"expat.so.4 E4x"I24444F
/l!"/ld-l!nux.so.2 GL /l!"/ld-l!nux.so.2 E4x34444444F
The critical library is l!"aprut!l-4.so.4 which must appear when you e%ecute ldd
:f you see the output above, your make process was successful Gou will need to run the
apxs tool a#ainst mod'()2so and copy that file and lib()(niso to the modules directory
of your "pache install
&. :f your make process is successful, you should follow the rest of the instructions in the
chapter <:nte#ratin# Tomcat 4 and "pache 2< to copy the relevant files to their
respective directories and edit the confi#uration files
:f you have any difficulties with this process, please post your ?uestion to the Tomcat8Users
mailin# list
Than)s #o to "ndrew &lute for this solutionM
!ppendi" D. 1clipse Tomcat and the Tomcat Deployer @Contriuted
y (atricia DarstenA
T'is solution +as contribute! by atricia %arsten. T'e actual te,t of t'e email 'as been
a!apte! for instructions.
These instructions involve the followin# componentsH
+clipse
"nt plu#in for +clipse
Tomcat 4 /eployer
D.1. !out the Tomcat Deployer
"ccordin# to the manual that comes with the tarball, the Tomcat 4 /eployer <allows deployin#
and undeployin# web applications to the Tomcat server, either statically Cthe application is setup
before the server is startedD, or dynamically Cin con(unction with the Tomcat 1ana#er web
application or manipulatin# already deployed applicationsD<
The Tomcat deployer is particularly useful if you use an :nte#rated /evelopment +nvironment
C:/+D and want to test your web applications on a runnin# Tomcat, without actually deployin#
the web application to Tomcat
D.2. Integrating the Tomcat Deployer% 1clipse and Tomcat
1 /ownload the Tomcat 4 /eployer tarball and untar it
2. &opy catal!na-deplo.er.war from jakarta-tomcat-5.4.25-deplo.er/l!" into
the eclipse ant plu#in folder, ecl!pse/plu5!ns/or5.apache.ant)1.5.>
3. &opy the followin# lines from the deployer3s "u!ld.xml C jakarta-tomcat-5.4.25-
deplo.er/"u!ld.xml D into +clipse3s pro(ect "u!ld.xml fileH
<target name="deploy" description="Deploy web application">
<deploy url="${url}" username="${username}" password="${password}"
path="${path}" war="${webapp.path}.war" update="true" />
</target>
4. 1a)e the necessary chan#es to the variable values in the deployer3s "u!ld.xml file to
reflect your own environmentH
<target name="deploy" description="Deploy web application">
<deploy url="${manager.url}" username="${manager.username}"
password="${manager.password}"
path="${app.path}" war="${dist.home}/${app.name}-$
{app.version}.war" update="true" />
</target>
&. Run ant with tar#ets all Cclean compileD, dist Ccreate war8fileD, deploy Ccopy
contents of build8folder to tomcatD, in this order The dist-target mi#ht not be
necessary because the deployer seems to use the contents of the build folder as its
input, not the war file Fn the other hand, : would not )now what to provide as correct
value for warS<< without #ettin# error messa#es
:f you have any difficulties with this process, please post your ?uestion to the Tomcat8Users
mailin# list

You might also like