Professional Documents
Culture Documents
1. Introduction
1.1 Web Application (Webapp)
A web application (or webapp), unlike standalone application, runs over the Internet.
Examples of webapps are google, amazon, ebay, facebook and twitter.
A webapp is typically a 3-tier (or multi-tier) client-server database application run over
the Internet as illustrated in the diagram below. It comprises five components:
1. HTTP Server : E.g., Apache HTTP Server, Apache Tomcat Server, Microsoft
Internet Information Server (IIS), nginx, Google Web Server (GWS), and others.
2. HTTP Client (or Web Browser) : E.g., Internet Explorer (MSIE), FireFox,
Chrome, Safari, and others.
3. Database : E.g., Open-source
MySQL,
Apache
Derby,
mSQL,
SQLite,
PostgreSQL, OpenOffice's Base; Commercial Oracle, IBM DB2, SAP SyBase, MS SQL
Server, MS Access; and others.
4.
Client-Side
A user, via a web browser (HTTP client), issues a URL request to an HTTP server
to start a webapp.
2.
3.
4.
5.
The server-side program receives the query parameters, queries the database
and returns the query result to the client.
6.
7.
HTTP is an application layer protocol runs over TCP/IP. The IP provides support for
routing and addressing (via an unique IP address for machines on the Internet);
while TCP supports multiplexing via 64K ports from port number 0 to 65535. The
HTTP is a pull protocol, a client pulls a page from the server (instead of server
pushes pages to the clients).
The syntax of the message is defined in the HTTP specification.
2.
3.
4.
5.
Tomcat 7.x (2010): RI for Servlet 3.0, JSP 2.2 and EL 2.2.
6.
Tomcat 8.x (2013): RI for Servlet 3.1, JSP 2.3, EL 3.0 and Java WebSocket 1.0.
Tomcat is an HTTP application runs over TCP/IP. In other words, the Tomcat server runs
on a specific TCP port in a specific IP address. The default TCP port number for HTTP
protocol is 80, which is used for the production HTTP server. For test HTTP server, you
can choose any unused port number between 1024 and 65535.
For Windows
1. Goto http://tomcat.apache.org Downloads Tomcat 8.0 "8.0.{xx}"
(where {xx} is the latest upgrade number) Binary Distributions Core
"ZIP" package (e.g., "apache-tomcat-8.0.{xx}.zip", about 8 MB).
2. Create your project directory, say "d:\myProject" or "c:\myProject". UNZIP the
downloaded file into your project directory. Tomcat will be unzipped into
directory "d:\myProject\apache-tomcat-8.0.{xx}".
3. For ease of use, we shall shorten and rename
this
directory
to
"d:\myProject\tomcat".
Take note of Your Tomcat Installed Directory. Hereafter, I shall refer to the Tomcat
installed directory as <TOMCAT_HOME>.
For Mac OS X
1. Goto http://tomcat.apache.org Download Tomcat 8.0 "8.0.{xx}"
(where {xx} denotes the latest upgrade number) Binary distribution
Core "tar.gz" package (e.g., "apache-tomcat-8.0.{xx}.tar.gz", about 8 MB).
2. To install Tomcat:
1. Goto "~/Downloads", double-click the downloaded tarball (e.g.,
"apache-tomcat-8.0.{xx}.tar.gz") to expand it into a folder (e.g.,
"apache-tomcat-8.0.{xx}").
2. Move the extracted folder
(e.g.,
"apache-tomcat-8.0.{xx}")
to
"/Applications".
3. For ease of use, we shall shorten and rename this folder to "tomcat".
Take note of Your Tomcat Installed Directory. Hereafter, I shall refer to the Tomcat
installed directory as <TOMCAT_HOME>.
For Ubuntu
Read "How to Install Tomcat 8 on Ubuntu". You need to switch between these two
articles.
For academic learning, I recommend " zip" (or "tar.gz") version, as you could simply
delete the entire directory when Tomcat is no longer needed (without running any uninstaller). You are free to move or rename the Tomcat's installed directory. You can
install (unzip) multiple copies of Tomcat in the same machine. For production, it is easier
to use the installer to properly configure the Tomcat.
Tomcat's Directories
Take a quick look at the Tomcat installed directory. It contains the following subdirectories:
bin : contains the binaries; and startup script ( startup.bat for Windows
and startup.sh for Unixes and Mac OS X), shutdown script ( shutdown.bat for Windows
and shutdown.sh for Unix and Mac OS X), and other binaries and scripts.
conf :
contains
the
system-wide
configuration
files,
such
could also place external JAR file (such as MySQL JDBC Driver) here.
logs : contains Tomcat's log files. You may need to check for error messages
here.
webapps : contains the webapps to be deployed. You can also place the WAR
(Webapp Archive) file for deployment here.
work : Tomcat's working directory used by JSP, for JSP-to-Servlet conversion.
temp : Temporary files.
JAVA_HOME=c:\Program Files\Java\jdk1.8.0_{xx}
JDK installed directory
(For Mac OS X)
Skip this step. No need to do anything.
web.xml
4.
tomcat-users.xml
context.xml
Locate the following lines (around Line 103) that define the "default" servlet; and
change the "listings" from "false" to "true".
<!-- The default servlet for all web applications, that serves static
-->
<!-- resources. It processes all requests that are not mapped to other -->
<!-- servlets with servlet mappings.
-->
<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>
This enables the manager GUI app for managing Tomcat server.
(for
Windows)
or
For Windows
Launch a CMD shell. Set the current directory to " <TOMCAT_HOME>\bin", and run
"startup.bat" as follows:
// Change the current directory to Tomcat's "bin"
// Assume that Tomcat is installed in "d:\myProject\tomcat"
d:
// Change the current drive
cd \myProject\tomcat\bin // Change Directory to YOUR Tomcat's "bin" directory
// Start Tomcat Server
startup
For Mac OS X
I assume that Tomcat is installed in " /Applications/tomcat". To start the Tomcat server,
open a new "Terminal" and issue:
// Change current directory to Tomcat's binary directory
cd /Applications/tomcat/bin
// Start tomcat server
./catalina.sh run
A new Tomcat console window appears. Study the messages on the console. Look out
for the Tomcat's port number (double check that Tomcat is running on port 9999). Future
error messages will be send to this console. System.out.println() issued by your Java
servlets will also be sent to this console.
......
......
xxx xx, xxxx x:xx:xx xx org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-9999"]
xxx xx, xxxx x:xx:xx xx org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
xxx xx, xxxx x:xx:xx xx org.apache.catalina.startup.Catalina start
INFO: Server startup in 2477 ms
Try issuing URL http://localhost:9999/examples to view the servlet and JSP examples. Try
running some of the servlet examples.
(Optional) Try issuing URL http://localhost:9999/manager/html to run the Tomcat Web
Manager. Enter the username and password configured earlier in tomcat-users.xml.
For Mac OS X
To shutdown the Tomcat server:
1. Press Control-C (NOT Command-C) on the Tomcat console; OR
2. Run the "<TOMCAT_HOME>/bin/shutdown.sh" script. Open a new "Terminal"
and issue:
3. // Change current directory to Tomcat's bin directory
4. cd /Applications/tomcat/bin
5.
6. // Shutdown the server
./shutdown.sh
WARNING : You MUST properly shutdown the Tomcat. DO NOT kill the cat by pushing
the window's "CLOSE" button.
First of all, choose a name for your webapp. Let's call it "hello". Goto Tomcat's "webapps"
sub-directory. Create the following directory structure for you webapp " hello" (as
illustrated):
1.
Under Tomcat's "webapps", create your webapp root directory "hello" (i.e.,
"<TOMCAT_HOME>\webapps\hello").
2.
3.
Under "WEB-INF", create a sub-sub-directory " classes" (case sensitive, plural) (i.e.,
"<TOMCAT_HOME>\webapps\hello\WEB-INF\classes").
You need to keep your web resources (e.g., HTMLs, CSSs, images, scripts, servlets, JSPs)
in the proper directories:
"hello": The is called the context root (or document base directory) of your
webapp. You should keep all your HTML files and resources visible to the web users
(e.g., HTMLs, CSSs, images, scripts, JSPs) under this context root.
"hello/WEB-INF": This directory, although under the context root, is not visible to
the web users. This is where you keep your application's web descriptor file
"web.xml".
"hello/WEB-INF/classes": This is where you keep all the Java classes such as
servlet class-files.
You should RE-START your Tomcat server to pick up the hello webapp. Check the
Tomcat's console to confirm that "hello" application has been properly depolyed:
......
INFO: Deploying web application directory D:\myProject\tomcat\webapps\hello
......
You can issue the following URL to access the web application "hello":
http://localhost:9999/hello
You should see the directory listing of the directory " <TOMCAT_HOME>\webapps\hello",
which shall be empty (provided you have enabled directory listing in web.xml earlier).
Create the following HTML page and save as " HelloHome.html" in your application's root
directory "hello".
1<html>
2 <head><title>My Home Page</title></head>
3 <body>
4 <h1>My Name is so and so. This is my HOME.</h1>
5 </body>
6</html>
You can browse this page by issuing this URL:
http://localhost:9999/hello/HelloHome.html
Alternatively, you can issue an URL to your web application root " hello":
http://localhost:9999/hello
The server will return the directory listing of your base directory. You can then click on
"HelloHome.html".
Rename "HelloHome.html" to "index.html", and issue a directory request again:
http://localhost:9999/hello
Now, the server will redirect the directory request to " index.html", if the root directory
contains an "index.html", instead of serving the directory listing.
You can check out the home page of your peers by issuing:
http://YourPeerHostnameOrIPAddress:9999/hello
http://YourPeerHostnameOrIPAddress:9999/hello/HelloHome.html
http://YourPeerHostnameOrIPAddress:9999/hello/index.html
with a valid "YourPeerHostnameOrIPAddress", provided that your peer has started his
tomcat server and his firewall does not block your access. You can use command such
as "ipconfig" (Windows), "ifconfig" (Mac OS X and Unix) to find your IP address.
(Skip Unless...) The likely errors are "Unable to Connect", "Internet Explorer
cannot display the web page", and "404 File Not Found". Read "How to Debug" section.
issuing
URLhttp://hostname:port/hello/sayhello from
their
browser,
as
Write the following source codes called "HelloServlet.java" and save it under your
application
"classes"
directory
(i.e.,
"<TOMCAT_HOME>\webapps\hello\WEB-
INF\classes\HelloServlet.java").
echos
some
request
(For Windows)
// Assume that Tomcat is installed in d:\myProject\tomcat
// Change directory to the source file
d:
cd \myProject\tomcat\webapps\hello\WEB-INF\classes
// Compile
javac -cp .;d:\myProject\tomcat\lib\servlet-api.jar HelloServlet.java
// Note: You need to enclose the jar file in double quotes if the path contains blank
//
e.g., javac -cp .;"d:\Path To\tomcat\lib\servlet-api.jar" HelloServlet.java
(For Mac OS X)
// Assume that Tomcat is installed in /Applications/tomcat
// Change directory to the source file
cd /Applications/tomcat/webapps/hello/WEB-INF/classes
// Compile
javac -cp .:/Applications/tomcat/lib/servlet-api.jar HelloServlet.java
The output of the compilation is " HelloServlet.class". Browse the "classes" folder to make
sure that it is created.
20 </servlet-mapping>
21</web-app>
In the above configuration, a servlet having a class file " HelloServlet.class" is mapped to
request URL "/sayhello" (via an arbitrary servlet-name "HelloWorld"), under this web
application "hello". In other words, the complete request URL for this servlet is
"http://hostname:port/hello/sayhello".
This configuration file, saved under your webapp " hello", is applicable only to this
particular webapp "hello".
RESTART your Tomcat server to refresh the "web.xml" file.
IMPORTANT: For EACH servlet, you need to write a pair of <servlet> and <servletmapping> elements with a common but arbitrary <servlet-name>. Take note that all
the <servlet> elements MUST be grouped together and placed IN FRONT of the <servletmapping> elements.
You shall see the output of the servlet displayed in your web browser.
Refresh the browser, you shall see a new random number upon each refresh. In other
word, the doGet() method of the servlet runs once per request.
Try "View Source" to look at the output received by the web users. Take note that the
web
users
receive
only
the
output
of
the
servlet
(generated
via
the out.println() statements). They have no access to the servlet programs (which may
contain confidential information).
(For Mac OS X's Safari browser) You need to enable "Developer Menu" under the
"Preferences" to enable the "View Source" menu.
<html>
<head><title>Hello, World</title></head>
<body>
<h1>Hello, world!</h1>
<p>Request URI: /hello/sayhello</p>
<p>Protocol: HTTP/1.1</p>
<p>PathInfo: null</p>
<p>Remote Address: 127.0.0.1</p>
<p>A Random Number: <strong>0.3523682325749493</strong></p>
</body>
</html>
(Skip Unless...) The likely errors are "404 File Not Found" and "500 Internal Server
Error". Read "How to debug" Section.
Start a MySQL client. I shall assume that there is a user called " myuser" with password
"xxxx".
// For Windows
cd {path-to-mysql-bin} // Check your MySQL installed directory
mysql -u myuser -p
// For Mac OS X
cd /usr/local/mysql/bin
./mysql -u myuser -p
Run the following SQL statements to create a database called " ebookshop", with a table
called "books" with 5 columns: id, title, author, price, qty.
create database if not exists ebookshop;
use ebookshop;
drop table if exists books;
create table books (
id
int,
title varchar(50),
author varchar(50),
price float,
qty int,
primary key (id));
insert into books values (1001, 'Java for dummies', 'Tan Ah Teck', 11.11, 11);
insert
insert
insert
insert
into
into
into
into
books
books
books
books
values
values
values
values
(1002,
(1003,
(1004,
(1005,
1<html>
2<head>
3 <title>Yet Another Bookshop</title>
4</head>
5<body>
6 <h2>Yet Another Bookshop</h2>
7 <form method="get" action="http://localhost:9999/hello/query">
8 <b>Choose an author:</b>
9 <input type="checkbox" name="author" value="Tan Ah Teck">Ah Teck
10 <input type="checkbox" name="author" value="Mohammad Ali">Ali
11 <input type="checkbox" name="author" value="Kumar">Kumar
12 <input type="submit" value="Search">
13 </form>
14</body>
15</html>
You can browse the HTML page by issuing the following URL:
http://localhost:9999/hello/querybook.html
Check a box (e.g., "Tan Ah Teck") and click the "Search" button. An HTTP GET request
will be issued to the URL specified in the <form>'s "action" attribute. Observe the URL
of the HTTP GET request:
http://localhost:9999/hello/query?author=Tan+Ah+Teck
The request consists of two part: a URL corresponding to the " action" attribute of
the <form> tag, and the "name=value" pair extracted from the <input> tag, separated
by a '?'. Take note that blanks are replaced by '+' (or %20), because blanks are not
allowed in the URL.
If you check two boxes (e.g., "Tan Ah Teck" and "Mohammad Ali"), you will get this URL,
which has two "name=value" pairs separated by an '&'.
http://localhost:9999/hello/query?author=Tan+Ah+Teck&author=Mohammad+Ali
You are expected to get an error "404 File Not Found", as you have yet to write the
server-side program.
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64}
Step 7(e) Confi gure the Request URL for the Servlet
Open the configuration file " web.xml" of your application " hello" that you have created
earlier for the HelloServlet, i.e., "<TOMCAT_HOME>\webapps\hello\WEB-INF\web.xml". Add
the lines that are shown in red at the LOCATIONS INDICATED.
1<?xml version="1.0" encoding="ISO-8859-1"?>
2<web-app version="3.0"
3 xmlns="http://java.sun.com/xml/ns/javaee"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-ap
6
7 <!-- To save as "hello\WEB-INF\web.xml" -->
8
9 <servlet>
10
<servlet-name>HelloWorld</servlet-name>
11
<servlet-class>HelloServlet</servlet-class>
12 </servlet>
13
14 <servlet>
15
<servlet-name>UserQuery</servlet-name>
16
<servlet-class>QueryServlet</servlet-class>
17 </servlet>
18
19 <!-- Note: All <servlet> elements MUST be grouped together and
20
placed IN FRONT of the <servlet-mapping> elements -->
21
22 <servlet-mapping>
23
<servlet-name>HelloWorld</servlet-name>
24
<url-pattern>/sayhello</url-pattern>
25 </servlet-mapping>
26
27 <servlet-mapping>
28
<servlet-name>UserQuery</servlet-name>
29
<url-pattern>/query</url-pattern>
30 </servlet-mapping>
31</web-app>
The above lines configure the following URL to invoke QueryServlet:
http://localhost:9999/hello/query
Select an author (e.g., "Tan Ah Teck") and click the submit button, which activates the
following URL coded in the <form>'s "action" attribute, together with the name=value
pair:
http://localhost:9999/hello/query?author=Tan+Ah+Teck
This URL "/query" triggers QueryServlet. The QueryServlet retrieves the name=value pair
of
"author=Tan+Ah+Teck".
Inside
the QueryServlet,
the
(Skip Unless...) The likely errors are "404 File Not Found" and "500 Internal Server
Error". Read "How to debug" Section.
30
out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");
31
out.println("</body></html>");
32
} finally {
33
out.close(); // Always close the output writer
34
}
35 }
36}
In Line 7, the annotation @WebServlet("/sayhi") is used to declare the URL mapping for
this servlet, i.e., http://localhost:9999/hello/sayhi. There is no need to provide any more
configuration in "web.xml"!
3. How to Debug?
"Everything that can possibly go wrong will go wrong." The most important thing to do is
to find the ERROR MESSAGE!!!
Always...
1.
Refresh your browser using Cntl-F5 (instead of refresh button or simply F5) to
get a fresh copy, instead of from the cache.
2.
You may re-start your Tomcat server. You may also re-start your browser to clear
the cache.
3.
Check your spelling! Always assume that all programs are case-sensitive. Don't
type, copy and paste if possible!
4.
b. If things were running fine until the lightning strikes, ask yourself "What have I
changed?"
Try running the script " configtest.bat" (for Windows) or "./configtest.sh" (for Mac
simply double-click the "shutdown.bat" or issue "shutdown" from CMD. For Mac OS
X, issue "./shutdown.sh" from Terminal.)
4.
If the error messages indicate that another application is running on the Tomcat's
port numbers, then you need to change the Tomcat's port number in server.xml.
You can issue command "netstat -an" to check the status of all the ports.
5. Start the tomcat in the debugging mode by running " catalina debug"
(or ./catalina.sh debug) and type "run" in the "jdb" prompt. Look for the error
messages.
In windows, start "Task Manager", Tomcat run as a "process" named " java.exe".
"java.exe".
In Linux/Mac OS X, you may issue " ps aux | grep tomcat" to locate the Tomcat
process. Note down the process ID (pid). You can kill the Tomcat process via " kill
-9 pid".
2.
2.
Check the Tomcat console to make sure that your application has been
deployed.
3.
4.
2.
3.
matching <servlet-
Apache Tomcat 7
More about the Cat
This article is meant for advanced programmers who is interested to know more about
Tomcat; or using Tomcat for production. For novices, read "How to Install and Get
Started with Tomcat".
The authoritative source of information on Tomcat is the Tomcat's documentation,
available under Tomcat's "webapps\docs" directory. You may also refer to the Java
Servlet, JSP and JSF specifications, as Tomcat is the Reference Implementation for these
technologies.
I shall assume that Tomcat is installed in d:\myproject\tomcat, and shall denote this
directory as <TOMCAT_HOME> or <CATALINA_HOME> - "Catalina" is the codename for
Tomcat 5 and above.
provides:
o
One Policy File: catalina.policy for specifying security policy.
Two Properties Files: catalina.properties and logging.properties,
Four Configuration XML Files: server.xml (Tomcat main configuration
o
o
web
application
deployment
logs :
contains
the
engine
logfile Catalina.{yyyy-mm-dd}.log,
host
logfile localhost.{yyyy-mm-dd}.log,
and
other
application
logfiles
such
as manger and host-manager. The access log (created by the AccessLogValve) is also
kept here.
host localhost.
work : contains the translated servlet source files and classes of JSP/JSF.
Tomcat is an HTTP server. Tomcat is also a servlet container that can execute Java
Servlet, and converting JavaServer Pages (JSP) and JavaServerFaces (JSF) to Java Servlet.
Tomcat employs a hierarchical and modular architecture as illustrated:
main
configuration
file
is
the
"server.xml",
kept
under
20
redirectPort="8443" />
21 <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
22
23 <Engine name="Catalina" defaultHost="localhost">
24
25
<Realm className="org.apache.catalina.realm.LockOutRealm">
26
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
27
resourceName="UserDatabase"/>
28
</Realm>
29
30
<Host name="localhost" appBase="webapps"
31
unpackWARs="true" autoDeploy="true">
32
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
33
prefix="localhost_access_log." suffix=".txt"
34
pattern="%h %l %u %t "%r" %s %b" />
35
</Host>
36 </Engine>
37 </Service>
38</Server>
Server
Server (Line 2) is top component, representing an instance of Tomcat.It can contains one
Listeners
The Server contains several Listeners (Lines 3-7). A Listener listens and responses to
specific events.
The JasperListener enables the Jasper JSP engine, and is responsible for recompiling the JSP pages that have been updated.
<Listener className="org.apache.catalina.core.JasperListener" />
defines
JNDI
name
the <Resource> element (Line 10-14), which is a memory-based database for user
authentication loaded from "conf/tomcat-users.xml".
<GlobalNamingResources>
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>
You can define other global resource JNDI such as MySQL database to implement
connection pooling.
Services
A Service associates one or more Connectors to a Engine. The default configuration
defines a Service called "Catalina", and associates two Connectors: HTTP and AJP to
the Engine.
<Service name="Catalina"> ...... </Service>
Connectors
A Connector is associated with a TCP port to handle communications between
the Service and the clients. The default configuration defines two Connectors:
protocol="HTTP/1.1"
connectionTimeout="20000"
The default chooses TCP port 8080 to run the Tomcat HTTP server, which is different
from the default port number of 80 for HTTP production server. You can choose any
number between 1024 to 65535, which is not used by any application, to run your
Tomcat
server.
The connectionTimeout attribute
define
the
number
of
milliseconds
this connector will wait, after accepting a connection, for the request URI line
(request
message)
to
be
presented.
The
default
is
20
seconds.
The redirect attribute re-directs the SSL requests to TCP port 8443.
AJP/1.3: Apache JServ Protocol connector to handle communication between
Tomcat server and Apache HTTP server.
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
You could run Tomcat and Apache HTTP servers together, and let the Apache HTTP
server handles static requests and PHP; while Tomcat server handles the Java
Servlet/JSP. Read "How To Configure Tomcat to work with Apache".
Containers
Tomcat refers to Engine, Host, Context, and Cluster, as container. The highest-level
is Engine;
while
the
lowest-level
is Context.
Certain
components,
such
as Realm and Valve, can be placed in a container.
Engine
A Engine is the highest-level of a container. It can contains one or more Hosts. You could
configure a Tomcat server to run on several hostnames, known as virtual host.
<Engine name="Catalina" defaultHost="localhost">
The Catalina Engine receives HTTP requests from the HTTP connector, and direct them to
the correct host based on the hostname/IP address in the request header.
Realm
A Realm is a database of user, password, and role for authentication (i.e., access
control). You can define Realm for any container, such as Engine, Host, and Context,
and Cluster.
<Realm className="org.apache.catalina.realm.LockOutRealm">
<Realm
className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>
</Realm>
The default configuration defines a Realm (UserDatabaseRealm) for the Catalina Engine,
to perform user authentication for accessing this engine.
name UserDatabase defined in theGlobalNamingResources.
It
uses
the
JNDI
Hosts
A Host defines a virtual
many Contexts (webapps).
host
under
the Engine,
which
can
in
turn
support
The default configuration define one host called localhost. The appBase attribute defines
the base directory of all the webapps, in this case, <CATALINA_HOME>\webapps. By
default, each webapp's URL is the same as its directory name. For example, the default
Tomcat
installation
provides
four
webapps: docs, examples, hostmanager and manager under the webapps directory. The only exception is ROOT, which
is identified by an empty string. That is, its URL is http://localhost:8080/.
The unpackWARs specifies whether WAR-file dropped into the webapps directory shall be
unzipped. For unpackWARs="false", Tomcat will run the application from the WAR-file
directly, without unpacking, which could mean slower execution.
The autoDeploy attribute specifies whether
the webapps directory automatically.
Cluster
to
deploy
application
dropped
into
Tomcat supports server clustering. It can replicate sessions and context attributes
across the clustered server. It can also deploy a WAR-file on all the cluster.
Valve
A Valve can intercept HTTP requests before forwarding them to the applications, for preprocessing the requests. A Valve can be defined for any container, such as Engine, Host,
and Context, andCluster.
In the default configuration, the AccessLogValve intercepts an HTTP request and creates
a log entry in the log file, as follows:
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
<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>
<!-- The mapping for the default servlet -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-====================
Default
Welcome
===================== -->
<!-- When a request URI refers to a directory, the default servlet looks -->
<!-- for a "welcome file" within that directory and, if present,
-->
<!-- to the corresponding resource URI for display. If no welcome file -->
<!-- is present, the default servlet either serves a directory listing, -->
<!-- or returns a 404 status, depending on how it is configured.
-->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
File
List
The above configuration maps URL "\" (root directory of the web context) (in <urlpattern>) to Java class DefaultServlet (in <servlet-class>) via the common 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>
</servlet>
<servlet-mapping>
<servlet-name>DirectoryListing</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
can
be
accessed
by
web
users
via
To change the request URL of the webapp, create a " context.xml" configuration file,
as follows, and place it under "ContextRoot\META-INF":
2.
Alternatively,
you
can
write
a <Context> element
......
4.
......
5.
6.
7.
8.
9.
In the above example, we define a web context with URL " /ws", with context root
(docBase or document base directory) at "d:\workshop". This application can be
accessed
via
URLhttp://host:port/ws.
Take note that:
o
The configuration creates a mapping from the "URL Path" issued by the
web users to the "document base directory" in the server's file system, where
you store your webapp resources.
Place
the <Context> element
before
the
ending
tag
of
slash '/' as
the directory
separator in
the
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
......
</host>
2. Deploying Webapps
A web context is a single web application (webapp). It is the lowest-level container, that
you can define components such as Realm and Valve. By default, all webapps are kept
under
the<CATALINA_HOME>\webapps directory
(as
configured
in
the <host> element appBase attribute.
A Java webapp may contain many types of files, such as HTML, CSS, Scripts, images,
JSP, servlet, utility classes, external library jar-files. A Java webapp must follow a
strict directory structure as depicted in the Servlet/JSP specifications. This enables
deployment in a Java-capable web server (such as Apache Tomcat and Glassfish). The
resources must be kept in the correct directories and sub-directories.
The URL of a webapp, by default, is the same as the base directory name (or context
root) of the webapp.
"ContextRoot": contains the resources that are visible and accessible by the web
clients, such as HTML, CSS, Scripts and images. These resources will be delivered to
the clients as it is. You could create sub-directories such as images, css and scripts,
to further categories the various resources.
"ContextRoot\WEB-INF": This directory, although under the context root, is NOT
visible to the web users. In other words, it is NOT accessible by the clients directly
(for security reason). This is where you keep your application-specific configuration
files such as "web.xml". It's sub-directories contain program classes, source files,
and libraries.
"ContextRoot\WEB-INF\src": Keeps the Java program source files. It is optional but
a good practice to separate the source files and classes to facilitate deployment.
"ContextRoot\WEB-INF\classes": Keeps the Java classes (compiled from the source
codes). Classes defined in packages must be kept according to the Java package
directory structure.
"ContextRoot\WEB-INF\lib": Keeps the libraries (jar-files), which are provided by
You
can
configure
webapp
in
many
ways:
(a)
Write
a <context> element
</icon>
<servlet-name>MyServlat</servlet-name>
<display-name>My Servlet Display Name</display-name>
<description>My Testing Servlet long description</description>
<servlet-class>MyServletClassname</servlet-class>
<init-param>
<param-name>myParmName</param-name>
<param-value>myParmValue</param-value>
</init-param>
<load-on-startup>25</load-on-startup>
</servlet>
......
<servlet-mapping>
<servlet-name>MyServlat</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
......
</web-app>
Drop the test.war into <CATALINA_HOME>\webapps. A context called test will be created
automatically. You can access the web application via URL http://host:port/test.
Tomcat
actually
unpacks
"test"
directory
3. Running Tomcat
3.1 Tomcat's Manager
References:
1.
2.
Tomcat "manager" webapp allows you to deploy a new web application; start, stop,
reload or un-deploy an existing one, without having to shut down and restart the server,
in a production environment.
2.
3.
Deploy a new webapp remotely, and undeploy a webapp without restarting the
container.
4.
Terminate (or Invalidate) sessions - a session has a pre-set expiry time (e.g., 30
sec).
5.
6.
Tomcat 7 provides separate manager roles for the GUI ( manager-gui), status (managerstatus),
http://{host}:{port}/manager/text/{command}?{parameters}
// Examples
http://{host}:{port}/manager/text/list
manager-jmx - Access to JMX proxy interface and to the "Server Status" page, via:
http://{host}:{port}/manager/jmxproxy/?{command}={parameter}
For security reason, a user should NOT be given more than one of the following
roles: manager-gui, manager-script, and manager-jmx.
documentation
The Tomcat service called "Apache Tomcat 7" is installed and will start automatically
whenever the system is started. Check the "Services" under "Control Panel"
"Administrative Tools".
A GUI application called Tomcat7w is available for monitoring and configuring Tomcat
services. Launch Tomcat7w:
<CATALINA_HOME>\bin> Tomcat7w
You could put the Tomcat icon in the system tray via the MS (Monitor Service) option:
Tomcat7w;
2.
3.
4.
5.
6.
7.
8.
9.
10.
To
uninstall
Tomcat
the <CATALINA_HOME>\bin\service.bat with remove option:
Service,
run
You can also use Microsoft Management Console (MMC) to manage the services: Go to
"Start" Run enter "services.msc".
A flip side of running Tomcat as a service is you need to read the error messages
from <CATALINA_HOME>\logs instead of the Tomcat console.
Alternatively, you could call the " catalina.bat|catalina.sh" directly, which provides more
options of starting Tomcat. Enter "catalina" to view the options:
<CATALINA_HOME>/bin> catalina
Using CATALINA_BASE: D:\xxx\tomcat7.0.{xx}
Using CATALINA_HOME: D:\xxx\tomcat7.0.{xx}
Using CATALINA_TMPDIR: D:\xxx\tomcat7.0.{xx}\temp
Using JRE_HOME:
d:\xxx\jdk1.6
Usage: catalina ( commands ... )
commands:
debug
Start Catalina in a debugger
debug -security Debug Catalina with a security manager
jpda start
Start Catalina under JPDA debugger
run
Start Catalina in the current window
run -security
Start in the current window with security manager
start
Start Catalina in a separate window
start -security Start in a separate window with security manager
stop
Stop Catalina
configtest
Run a basic syntax check on server.xml
version
What version of tomcat are you running?
Study the source codes of " catalina.bat|catalina.sh". Take note that the environment
variable JAVA_HOME is needed in this script.
The other scripts provided are:
as "catalina configtest".
version.bat|version.sh: for displaying the versions, same as "catalina version".
digest.bat|digest.sh: making password hash and encrypting password.
Internal
4. Security
4.1 Realm and User Authentication in Tomcat
References:
1.
"Realm
Configuration
HOW-TO"
(@
"<CATALINA_HOME>\webapps\docs\realm-
howto.html").
2.
In Information Security:
Access control deals with identifying which resources require protection, and
network. This is often carried out via employing HTTP over SSL (Secure Socket
Layer), known as HTTPS.
Message Integrity ensures that messages are not tempered during transmission.
Security can be managed by the webapps themselves (called applicationmanaged security) or via the Tomcat container (called container-managed security). In
container-managed security, security is handled by the server. The server-side programs
(servlets, JSPs) do not need any security-aware code. That is, the security control is
totally transparent to the server-side programs. This section shall deal with containermanaged security for access control and authentication.
In Tomcat, a user is identified via username/password. A user is assigned role(s) (e.g.,
manager, admin, user, etc). Tomcat grants access for webapps to role(s), instead of
individual users.
A realm is a collection of usernames/passwords and roles. Tomcat supports the following
types of realms:
Authentication
and
Authorization Service).
You
can
used
the <realm> element
to
configure
a
realm
in
"conf\server.xml". <realm> element can be placed in <engine>, <host>, or <context>,
which determines the scope of the realm: all virtual hosts under the engine, a particular
host, or a particular web application.
4.2 UserDatabaseRealm
UserDatabaseRealm stores user information in a XML file and accessed via JNDI (Java
Naming
and
Directory
Interface).
By
default,
the
XML
file
is
"conf\server.xml"
You can specify the type of realm to be used via <Realm> element in server.xml. In this
case, UserDatabaseRealm. The <Realm> is defined within the <Engine> elements, and
thus applicable to all the virtual hosts and webapps, under this server.
To specify the file used in UserDatabaseRealm, a JDNI resource named "UserDatabase" is
defined, which maps to the file "conf\tomcat-users.xml".
<Server ...... >
<!-- Global JNDI resources -->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users -->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>
<Service name="Catalina">
<Engine name="Catalina" defaultHost="localhost">
<!-- Use the LockOutRealm to prevent attempts to guess user passwords
via a brute-force attack -->
<Realm className="org.apache.catalina.realm.LockOutRealm">
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase" />
</Realm>
<Host name="localhost" ......
......
</Host>
</Engine>
</Service>
</Server>
"conf\tomcat-users.xml"
Recall that a user is identified via username/password. A user is assigned role(s).
Accesses for web applications are granted to role(s) instead of individual users. " Tomcat-
Uncomment them for testing the example. Two roles, tomcat and role1, and three
users, tomcat, role1 and both are defined.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<tomcat-users>
<role rolename="tomcat" />
<role rolename="role1" />
Take note that the passwords are stored in clear text, which is not really desirable.
"ContextRoot\WEB-INF\web.xml"
For Tomcat's webapp called " examples", the security roles are defined using <securityconstraint> element in "webapps\examples\WEB-INF\web.xml" as follows. The URL
patterns/jsp/security/protected/* are
of tomcat and role1 only.
accessible
by
users
<web-app ......>
......
<security-constraint>
<display-name>Example Security Constraint</display-name>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<!-- Define the context-relative URL(s) to be protected -->
<url-pattern>/jsp/security/protected/*</url-pattern>
<!-- If you list http methods, only those methods are protected -->
<http-method>DELETE</http-method>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>PUT</http-method>
</web-resource-collection>
<auth-constraint>
<!-- Anyone with one of the listed roles may access this area -->
<role-name>tomcat</role-name>
<role-name>role1</role-name>
</auth-constraint>
</security-constraint>
having
roles
The
login
page
submits
the
username
and
password
in
used. For robust session tracking, all URLs emitted by server-side programs (servlet/JSP)
should be run through this method.
If login fails, user will be redirected to error.jsp page, as follows,
<html>
<head><title>Error Page For Examples</title></head>
<body>
Invalid username and/or password, please try again
<a href='<%= response.encodeURL("index.jsp") %>'>again</a>.
</body>
</html>
If login succeeds, the user will get the page he requested for. Study the
"examples\jsp\security\protected\index.jsp" source.
You
can
use request.getRemoteUser() to
get
the
authenticated
login
4.4 HTTPS
In FORM-based authentication, the username/password are sent in clear text, and
susceptible to eavesdropping. Hence, it is important to encrypt the transport by turning
on SSL (HTTPS). Read "Tomcat with SSL" on how to setup Tomcat with SSL.
To
enforce
user
to
use
secure
transport
(HTTPS),
add
a <transportguarantee>CONFIDENTIAL</transport-guarantee>,
inside
the <security-constraint>,
follows:
<security-constraint>
<display-name>Example Security Constraint</display-name>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/jsp/security/protected/*</url-pattern>
......
</web-resource-collection>
<auth-constraint>
<role-name>tomcat</role-name>
......
</auth-constraint>
<!-- must use SSL for secure transport -->
as
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
All
accesses
to
HTTP
at
port
8080
(e.g.,
http://localhost:8080/examples/jsp/security/protected/index.jsp) will be redirected to
HTTPS
at
port
8443
https://localhost:8443/examples/jsp/security/protected/index.jsp).
(e.g.,
In BASIC authentication, Tomcat uses the HTTP Basic Authentication to ask for username
and password. Try http://localhost:8080/examples/jsp/security/protected/index.jsp, you will
be prompted for username/password automatically. There is no redirect to login.jsp and
no need to write the login.jsp.
Again, the HTTP Basic Authentication sends the username and password in clear text
(password is encoded in Base64, but not encrypted). It is totally insecure, unless you
use a secure transport (HTTPS) or VPN (Virtual Private Network).
The Tomcat's webapp manager (under webapps/manager) uses BASIC authentication.
4.7 JDBCRealm
UserDatabaseRealm is not meant for serious production environment, as it is hard to
Setting up Database
We shall set up our user database in MySQL. Read "How to Install MySQL and Get
Started" if you are new to MySQL.
The following script can be used to set up the user database. Two tables are required:
a users table containing username and password, and a user_roles containing username
and the role assigned.
create database tomcat_users;
use tomcat_users;
JDBC Driver
Next, copy the MySQL's JDBC driver ("mysql-connector-java-5.1.{xx}-bin.jar") into
Tomcat's lib ("<CATALINA_HOME>\lib"). Read "How to Install MySQL and Get Started"
"conf\server.xml"
Again, the realm is defined in server.xml via a <Realm> element. In this case,
a JDBCRealm, with a connectionURL providing a MySQL database connection.
<Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:{port}/tomcat_users"
connectionName="{dbuser}"
connectionPassword="{dbpassword}"
userTable="users" userNameCol="username" userCredCol="password"
userRoleTable="user_roles" roleNameCol="role" />
Replace
the {port} with
your
MySQL
server
port
and {dbuser} and {dbpass} with an authorized MySQL username/password.
number,
"ContextRoot\WEB-INF\web.xml"
Same as UserDatabaseRealm.
Authentication Methods
Same
as UserDatabaseRealm,
you
can
method.
Testing
You need to start MySQL server before starting the Tomcat Server.
SSL (Secure Socket Layer), allows web browsers and web servers to communicate over
a secured (encrypted) connection. Tomcat provides built-in support for SSL.
Read:
"SSL
Configuration
How-to"
of
Tomcat
Documentation
"<CATALINA_HOME>\webapps\docs\ssl-howto.html".
Step 1: Check your JDK version. Tomcat's SSL uses Java Secure Socket Extension
(JSSE), which has been integrated into JDK since 1.4.
Step 2: Prepare the Tomcat's server certificate, using the JDK's Key and Certificate
Management Tool called "keytool" (in "<JAVA_HOME>\bin" ), as follows:
> keytool
... display the help menu ...
// Generate a self-signed certificate for Tomcat
>
keytool
-genkey
-alias
tomcat
-keyalg
RSA
-keystore
{TOMCAT_HOME}\conf\.keystore
Enter keystore password: xxxxxxxx
Re-enter new password: xxxxxxxx
What is your first and last name?
[Unknown]:
What is the name of your organizational unit?
[Unknown]:
What is the name of your organization?
[Unknown]:
What is the name of your City or Locality?
[Unknown]:
What is the name of your State or Province?
[Unknown]:
What is the two-letter country code for this unit?
[Unknown]:
Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown
correct?
[no]: y
Enter key password for <tomcat>
(RETURN if same as keystore password):
The "-genkey" option is used to generate a public-private key pair. The public key
is wrapped into an X.509 v1 self-signed certificate. The certificate and the private
key are stored in a new keystore entry identified by the alias. In our case, the alias
name must be "tomcat".
The "-keyalg" option specifies the key generation algorithm. RSA public key
algorithm is used in this case.
The "-keystore" option specifies the name and location of the key store file.
The password for alias tomcat must be the same as the keystore (i.e., hit enter
Note that the SSL (or HTTPS) is running on port 8443 instead of its default port number
443.
Add in the keystoreFile and keyStorePass attributes. The keystoreFile attribute specified
the location of the keystore file. The keyStorePass provides the password for accessing
the keystore file.
Step 4: Start your tomcat (run "<CATALINA_HOME>\bin\startup.bat"). After that, start a
web browser and issue an HTTPS request as follows:
https://localhost:8443
5. Clustering
[TODO]
directory="logs"
prefix="mytest.com_access_log." suffix=".log"
pattern="%h %l %u %t "%r" %s %b"
resolveHosts="false" />
</Host>
</Engine>
The above lines configure a virtual host with hostname " www.mytest.com", with
webapps base directory at "<CATALINA_HOME>\webapps_mytest.com". We also define a
alias
called
"mytest.com".
That
is,
this
host
can
be
accessed
via http://www.mytest.com:port or http://mytest.com:port. We also define a Valve, which
intercepts the request message to write a log entries (similar to localhost).
Next:
1.
2.
Create a web application called ROOT, by creating a directory ROOT under the
"webapps_mytest.com". Recall that ROOT was configured with an empty string URL.
Write
a
welcome
page
"webapps_mytest.com\ROOT".
called
"index.html"
5.
<html>
6.
7.
<body>
8.
9.
and
save
it
in
</html>
To test the virtual host, without registering the hostname with an ISP, edit
"C:\Windows\System32\drivers\etc\hosts"
administrative authority):
to
include
the
following
lines
(required
127.0.0.1 www.mytest.com
127.0.0.1 mytest.com
These lines maps host names www.mytest.com and mytest.com to IP address 127.0.0.1,
which is the localhost. As the IP software checks the host file before asking Domain
Name Service (DNS) to resolve a host name, you willl be able to test your virtual host.
Now, you are ready to test the virtual hosts. Start the Tomcat server and issue these
URL:
http://www.mytest.com:8080
http://mytest.com:8080
http://www.mytest.com:8080/
http://mytest.com:8080/
http://www.mytest.com:8080/index.html
http://mytest.com:8080/index.html
"Clustering/Session
Replication
HOW-TO"
" webapps/docs/cluster-
howto.html".