Notes on Tomcat Servlets and JSPs - The Risberg Family

infestationwatchΛογισμικό & κατασκευή λογ/κού

28 Οκτ 2013 (πριν από 3 χρόνια και 7 μήνες)

109 εμφανίσεις

Page
1

of
10

Notes on Tomcat, Servlets, and JSP’s

Created
0
1/15/05

Updated
0
2/23/05
,
Updated
0
3/
0
5/05
,
Updated 06/28/06
,
Updated 09/08/06
, Updated 03/15/08
,

Updated 07/23/08

Updated 11/30/08
, Updated 01/13/09
, Updated 07/05/09
, Updated 10/31
/09
, Updated 02/20/10
, Updat
ed 04/13/10

Updated 08/20/10
, Updated 10/09/10
, Updated 02/28/11
, Updated 05/31
/11
, Updated 09/16/11
, Updated 11/11
/11

Updated 02/15/12
, Updated 05/10
/13
, Updated 08/04/13

Introduction

Jakarta Tomcat is a freeware, open source, Java
-
based Web application c
ontainer that was created to run servlet
-
based and Java Server Page
-
based web applications. The Tomcat server has become the reference implementation
for both the servlet and JSP specifications. Some of the additional features provided by Tomcat include
the Tomcat
Manager
web
application, specialized

security

realm implementation,
JNDI support,
and Tomcat valves. These
features
enhance the
capability and
customizability of the server.


The current release is Tomcat 7.0, but t
his document describes Tomcat

6.0. Earlier versions

of this document have

described Tomcat
5.0 and Tomcat 5.5, with some background information based on Tomcat 4. At Incra

and Menlo
School
, we began using Tomcat 3.3 in April 2002,
and
then changed to

Tomcat 4.0 in January 2003. W
e
changed to
Tomcat 5.0 in early
2005

and to Tomcat 5.5 in early 2006.

W
e

began using Tomcat 6.0 in early 2008.

We updated
to the 6.0.29 release in October 2010, and also placed that release onto our Slicehost account
.

We updated to the
6.0.32 release in
February 2011
. We updated to 6.0.33 in November 2011
on the T410.

We update
d to the current
version 6.0.37

in May

2013
.


The Tomcat Manager w
eb application is installed in the context path /manager
/html

and provides the basic
functionality to manage appl
ications running in the server, such as
install, start, stop, and restart


Tomcat provides two methods for protecting resources. The first authentication implementation provided with
Tomcat is a memory
-
based system, in which the permissions are read from
a configuration file and maintained in
memory. The second approach is a JDBC realm, which stores all of its permission information in a user
-
defined
JDBC
-
compliant database.


This document also contains material on servlets, includ
ing differences between
2.3,
2.4
, and 2.5

specifications, as
well as material on JSP’s, including the JSP 2.0 specification. The JSP 2.0 spec was released and implemented only
in 2003/04, as the prior JSP 1.1 spec was current for a number of years before that.


Tomcat continues
to be one of the most popular web servers, with Jetty being perhaps the second most popular.
Others such as Resin have been used less and less
. J
Boss uses Tomcat as its servlet container, while WebSphere has
its own implementation of a servlet container.

Background Information on Tomcat, Servlets, and JSP’s

“Tomcat:

The Definitive Guide
, Second Edition
” by Jason Brittain, and Ian Darwin. O’Reilly

Press
,
October 2007
,

494 pages
.

List price
$39.95
, Amazon price $23.99, used from $19.55.


Second edition
updates the text to Tomcat
6.0 and is well
-
rated.
The first edition came out in mid
-
2003, covered

Tomcat version 4, and wa
s well
-
rated.
Focuses on administration and deployment, including how to integrate with
the
Apache web server. Little material
on d
evelo
pment.


“Professional Apache Tomcat 6
”, by Vivek Chopr
a, et. al., Wrox Press, August

2007
.

List price

$39.95. Covers
deployment, configuration, clustering, etc. Load balancing, linking with web servers, and development tools such

as
NetBeans, JBuil
der, Eclipse
.


“Tomcat 5 Unleashed” by Lajos Maczor. Sams Press, August 2004
, 768 pages. List price $49.99
. Limited reviews
so far.


Page
2

of
10

The
Tomcat web site has a great deal of documentation on configuring and customizing Tomcat, including the
interfaces th
at must be implemented by custom components. Also contains some discussion of the Manager
application, and the default servlet.


The Servlet and JSP specification documents are on the Sun web site.


“Java Servlet Programming” by Jason Hunter with William
Crawford, Second Edition. O’Reilly

Press
, April 2001.
Covers servlet specification 2.2 and 2.3 draft. Lots of great examples, including images, database, template engines,
etc. Doesn’t have much coverage of JSP’s.


“Core Servlets and Java Server Pages
” by Marty Ha
ll, Second Edition (we

have the first edition). Prentice
-
Hall,
August 2003.
List price
$49.95
.

First edition has good balance of servlet and JSP discussion, including examples of
combining both. Well
-
regarded in reviews. Even has discussi
on and examples of writing custom tags. But no
dis
cussion of template engines or S
truts. Second edition has material on servlet 2.4 and JSP 2.0
.
Struts will be in
volume 2, but that is not yet published.

Structure of a Web Application

According to the s
pecification, “a web application is a collection of servlets, html pages, classes, and other resources
that can be bundled and run on multiple containers from multiple vendors

. This means the following:




Servlets



JSP’s



Utility classes



Static documents in
cluding HTML and images



Client side classes



Meta
-
information describing the web application


The directories of a web application are


/<appName>


Root directory. All jsp, html, and image files are contained here.
Typically we put these into directories
under the root, such as “jsp”,
“images”, etc.



L<appkame>LtbB_fkc

Contains classes and the deployment descriptorI web.xml

L<appkame>LtbB_fkcLclasses

there servlet and utility classes are located

L<appkame>LtbB
J
fkcLlib

Contains gava archive files that t
he app usesI such as gaBC driver classes
in a gAo file.


qhe deployment descriptor containsW



The servlet mapping information



Security information

Relationship between Tomcat and EJB servers

The following notes from Dan Allen’s book on Seam (2008) compared

Tomcat and EJB servers quite well:


Once upon a time, the industry flocked to Tomcat while fleeing a bad relationship with
J2EE
application
servers. Developers wrote them off because they were expensive, slow, and heavyweight, and led to vendor
Page
3

of
10

lock
-
in.
Tomcat represented the grassroots movement and let developers feel more free. Today, Tomcat is
the most widely used

“application server.”


The main problem with Tomcat is that it isn’t a Java
EE

compliant application server

it’s a servlet
container. Altho
ugh it made sense to cut corners at the time when
J2EE
servers had grown fat and
expensive, times have changed. The Java
EE
5 application servers have escaped their legacy and are now
fast and cheap (GlassFish, for instance, is open source and starts in u
nder a second). Furthermore,
application servers adhere to a stack of successful and progressive specifications and offer all the services
that you need to support transactional applications right out of the box. In my opinion, Java
EE
application
server
s offer a much better development experience than a servlet container like Tomcat.


You can even argue that Tomcat is now the culprit of vendor lock
-
in.

It requires you to bend your
application over backward to get it to work in this nonstandard environme
nt, whereas all other application
servers can theoretically share applications with little effort.

That’s why the preferred solution for
deploying an application that uses
EJB
3 or
JTA
to Tomcat is to make Tomcat act like a Java
EE
5
application server ra
ther than forcing the application to fit Tomcat’s expectations.

Tomcat Architecture

At the core of Tomcat 4 and later is the Catalina servlet engine, which acts at the top
-
level container for all Tomcat
instances. The structure of a running instance is co
mposed of a collection of functional components, each with a
specific role. The sum of all of these contains makes up an instance of the Catalina engine. The server.xml
configuration file defines all of these components.


<server>


<service>



<connect
or />



<engine>




<host>





<context>





</context>




</host>



</engine>


</service>

</server>


This instance can be organized into a set of containers including a server, and a context. The server.xml file is the
structure and content of the initia
lization of the Tomcat server, as each element specifies the class to instantiate, and
the configuration parameters.


In the Tomcat world, a Server represents the whole container.

Tomcat provides a default implementation of the
Server interface
, and this is rarely customized by users.


A Service is an intermediate component which lives inside a Server and ties one or more Connectors to exactly one
Engine. The

Service element is rarely customized by users, as the default implementation is simple and sufficient:
Service interface
.


A Connector handles communicati
ons with the client.


There are multiple connectors available with Tomcat, all of
which implement the
Connector interface.


These include the
Coyote connector

which is used for most HTTP traffic,
especially when running Tomcat as a standalone server, and the
JK2 connector

w
hich implements the AJP protocol
used when connecting Tomcat to an Apache HTTPD server.

Creating a customized connector is a significant effort


An Engine represents a request processing pipeline for a specific Service.

As a Service may have multiple
Con
nectors, the Engine received and processes all requests from these connectors, handing the response back to the
appropriate connector for transmission to the client.

The
Engine interface

may be implemented to supply custom
Engines, though this is uncommon.

Page
4

of
10


Note that the Engine may be used for Tomcat server clustering via the jvmRoute parameter.

Read the Clustering
documentation for more information


A Hos
t element defines the virtual hosts that are contained in each instance of a Catalina engine. Each Host can be a
parent to one or more applications which being presented by a Context component.


A Context represents a web application.

A Host may contain
multiple contexts, each with a unique path.

The
Context interface

may be implemented to create custom Contexts, but this is rarely the case because the
StandardContext

provides significant additional functionality


Other facilities that can be added to the Tomcat configuration through server.xml

include security realms and
loggers.

History of Tomcat Versions

Tomcat 4 was mostly about the partitioning of the Catalina engine into its components. Tomcat 5 connects this
effort with the effort started in Tomcat 3, which was about management and admin
istration.


Tomcat 4.1 added the new Coyote connector, which improved the performance of each HTTP connection and
request processing.


Starting with Tomcat 5, they have begun efforts to make more aspects of Tomcat manageable via JMX.

In addition,
the Mana
ger and Admin webapps have been greatly enhanced and improved.

Manageability is a primary area of
concern for us as the product matures and the specification becomes more stable. Clustering and load balancing
have been introduced.


In addition, Tomcat 5
implements the servlet 2.4 specification and the JSP 2.0 specification. It also has performance
optimization and reduced garbage collection. Better taglibs handling and pooling. Most recent production release is
5.0.28.


Tomcat 5.5 moves ahead to offer
mostly changes under the hood, in performance, stability, and reduced total cost of
ownership. The current production
-
quality

release is 5.5.25
.


Tomcat 6.0 implements
servlet
2.5 and JSP 2.1, and is
a
major reimplementation of several configuration facil
ities,
and administration. The current prod
uction
-
quality release is 6.0.3
7
, released in
late April 2013
.


Tomcat 7.0

was
released in late 2010.

Notes on Configuration of Tomcat

One important step is to tell Tomcat to check the modification dates of the c
lass files of requested servlets, and
reload ones that have changed since they were loaded into the server's memory. This slightly degrades performance
in deployment situations, so is turned off by default. However, if you fail to turn it on for your dev
elopment server,
you'll have to restart the server every time you recompile a servlet that has already been loaded into the server's
memory.

So, edit
install_dir/conf/
context
.xml

and change



<Context>


To



<Context

reloadable="true" privileged="tr
ue">



Note that the
privileged

entry is really to support the invoker servlet, so you can omit that entry if you do not
use the invoker.



Page
5

of
10

How to configure memory settings for Tomcat: the default memory setting is 64MB. We commonly change this to
102
4MB (1 GB). To do this, go to the

/bin directory. In the catalina
.bat file, add the following line:



set JAVA_OPTS=

Xmx1024m


The primary files that configure Tomcat are located in the /conf directory of the deployment and include:



server.xml


the prim
ary configuration file, this contains a multi
-
layer description of runtime components
including connectors and containers. Essentially this is the file that “builds” the runtime, just as a struts
configuration builds the runtime of actions and forms. It
may even be that this file is read by Digester as
the struts file is.



context.xml


similar to server.xml, but loaded for each web application.



tomcat
-
users.xml


used to define manager user login information, and can also be used to configure the
login ma
nagement provided by the Tomcat container, which could be used by sim
ple web applications
.



catalina.policy


a set of security definitions, providing declarative security over HTTP request processing.



catalina.properties


properties for loading and cachin
g of content within Catalina. It is not clear why these
are not in server.xml, perhaps it was due to a difference in development groups



logging.properties


used to configure the logging within Tomcat, and can be set to reduce the number of
messages and w
arnings generated at start
-
up time.



w
eb.xml



this document defines default values for *all* web applications, loaded into this instance of
Tomcat. As each application is deployed, this file is processed, followed by the “/WEB
-
INF/web.xml"
deployment desc
riptor from your own applications.


The structure of server.xml is as follows:




Top Level Elements

-

<Server> is the root element of the entire configuration file, while
<
Service>
represents a group of Connectors that is associated with an Engine.



Connect
ors

-

Represent the interface between external clients sending requests to (and receiving responses
from) a particular Service.



Containers

-

Represent components whose function is to process incoming requests, and create the
corresponding responses. An En
gine handles all requests for a Service, a Host handles all requests for a
particular virtual host, and a Context handles all requests for a specific web application.



Nested Components

-

Represent elements that can be nested inside the element for a Conta
iner. Some
elements can be nested inside any Container, while others can only be nested inside a Context.


By default, Tomcat 5.5
and later
attempts to save all objects that are stored in the session object every time it shuts
down. This may cause Tomcat
to display error messages when it shuts down and when it restarts after an
unsuccessful shutdown.

Since some applications

weren’t designed to persist across Tomcat restarts, there’s no need
to attempt to save the objects stored in the session object when
shutting down Tomcat.


To turn serialization off, open the context.xml file that’s stored in Tomcat’s conf directory and remove the
comments from this element:


<Manager pathname="" />


See also the notes below about configuring Tomcat
to

work with remo
te debugging.

Tomcat Log Files

Tomcat logs are organized as follows. In /root/apache
-
tomcat
-
<version>, see the following:



catalina
-
<date>.log shows high
-
level logging



localhost
-
<date>.log shows detailed logging

Page
6

of
10

Tomcat Manager for Administration

In many pr
oduction environments, it is very useful to have the capability to deploy a new web application, or
undeploy an existing one, without having to shut down and restart the entire container.

In addition, you can request
an existing application to reload itse
lf, even if you have not declared it to be
reloadable

in the Tomcat

server
configuration file.


To support these capabilities, Tomcat 5

and later include

a web application (installed by default on context path
/manager

or
/manager/html
) that supports the f
ollowing functions:




Deploy a new web application from the uploaded contents of a WAR file.



Deploy a new web application, on a specified context path, from the server file system.



List the currently deployed web applications, as well as the sessions that

are currently active for those web
apps.



Reload an existing web application, to reflect changes in the contents of
/WEB
-
INF/classes

or
/WEB
-
INF/lib
.



List the OS and JVM property values.



List the available global JNDI resources, for use in deployment to
ols that are preparing
<ResourceLink>

elements nested in a
<Context>

deployment description.



List the available security roles defined in the user database.



Start a stopped application (thus making it available again).



Stop an existing application (so t
hat it becomes unavailable), but do not undeploy it.



Undeploy a deployed web application and delete its document base directory (unless it was deployed from

the

file system).


The visual appearance of the manager is as follows:



The “Server Status” lin
k on the Manager main screen produces:


Page
7

of
10



A default Tomcat installation includes the manager.

To add an instance of the Manager web application
Context

to
a new host install the
manager.xml

context configuration file in the
$CATALINA_HOME/conf/[enginenam
e]/[hostname]

folder. Here is an example:


<Context path="/manager" debug="0" privileged="true"


docBase="/usr/local/kinetic/tomcat5/server/webapps/manager">

</Context>


You also need to define a Tomcat user with the manager role. This can be don
e by changing tomcat
-
users.xml in the
/conf directory to read:


<?xml version='1.0' encoding='utf
-
8'?>

<tomcat
-
users>


<role rolename="manager"/>


<user username="admin" password="123456" roles="manager"/>

</tomcat
-
users>


If you have Tomcat configured

to support multiple virtual hosts (websites) you would need to configure a Manager
for each.


There are three ways to use the
Manager

web application.



As an application with a user interface you use in your browser.

Here is an example URL where you can
replace
localhost

with your website host name:
http://localhost/manager/html/

.



A minimal version using HTTP requests only which is suitable for use by scripts setup by system
administrators. Commands are given as part of the request URI, and responses ar
e in the form of simple
text that can be easily parsed and processed.



A convenient set of task definitions for the
Ant

(version 1.4 or later) build tool.


There is also a facility to configure Tomcat at runtime using JMX.

Using JNDI in Tomcat

Tomcat prov
ides a JNDI
InitialContext

implementation instance for each web application running under it, in a
manner that is compatible with those provided by a
J2EE

application server. The J2EE standard provides a standard
Page
8

of
10

set of elements in the
/WEB
-
INF/web.xml

fi
le to reference resources; resources referenced in these elements must
be defined in an application
-
server
-
specific configuration.


For Tomcat, these entries in per
-
web
-
application
InitialContext

are configured in the
<Context>

elements that
can be specif
ied in either
$CATALINA_HOME/conf/server.xml

or, preferably, the per
-
web
-
application context
XML file (either
META
-
INF/context.xml
).


Tomcat maintains a separate namespace of global resources for the entire server. These are configured in the
<GlobalName
ingResources>

element of
$CATALINA_HOME/conf/server.xml
. You may expose these
resources to web applications by using
<ResourceLink>

elements.


The resources defined in these elements may be referenced by the following elements in the web application
depl
oyment descriptor (
/WEB
-
INF/web.xml
) of your web application:



<env
-
entry>

-

Environment entry, a single
-
value parameter that can be used to configure how the
application will operate.



<resource
-
ref>

-

Resource reference, which is typically to an object fa
ctory for resources such as a
JDBC
DataSource
, a JavaMail
Session
, or custom object factories configured into Tomcat 5.



<resource
-
env
-
ref>

-

Resource environment reference, a new variation of
resource
-
ref

added
in Servlet 2.4 that is simpler to configure
for resources that do not require authentication information.

The
InitialContext

is configured as a web application is initially deployed, and is made available to web
application components (for read
-
only access). All configured entries and resources ar
e placed in the
java:comp/env

portion of the JNDI namespace, so a typical access to a resource
-

in this case, to a JDBC
DataSource

-

would look something like this:





// Obtain our environment naming context

Context initCtx = new InitialContext();

Context envCtx = (Context) initCtx.lookup("java:comp/env");


// Look up our data source

DataSource ds = (DataSource)
envCtx.looku
p("jdbc/EmployeeDB");


// Allocate and use a connection from the pool

Connection conn = ds.getConnection();

... use this connection to access the database ...

conn.close();


Valves and Filters in Tomcat 4.0 and Later

A Tomcat value, which is a new feature
in Tomcat 4, allows you to associate an instance of a Java class with a
particular Catalina container. This instance acts as a preprocessor for each request. These classes are called
“valves”, because they intercept and can control processing of requests

between the different layers of the Catalina
request processing pipeline. There is a standard interface for Valves, defined in
org.apache.catalina.Valve
.


The parts of the Tomcat configuration that can host a valve are:



Engine



Host



Context


The four type
s of valves which are currently defined are:



Access Log


carries out logging



Remote Access Filter


does security checking



Remote Host Filter


does security checking

Page
9

of
10



Request Dumper


carries out logging


The Access Log valve is defined through a configur
ation such as:


<valve className=”org.apache.catalina.valves.AccessLogValve”


directory=”logs” prefix=”localhost_access_log.”


suffix=”txt” pattern=”common” />


The Remote
a
ccess filter allows the configuration to accept or deny f
rom IP address which matches or doesn’t match
a pattern. An example would be:


<valve className=”org.apache.catalina.valves.RemoveAddrValve”


deny=”127.*” />


The other valves are similar in structure.


Filters are another facility in Tomcat
4 and later, which associate servlet invation with a URL pattern. For instance,
in the Struts and Incra frameworks filters are used to have all patterns ending in “.do” get process by the
MainServlet.


Filter classes can be implemented that are similar to

a servlet, having a lifecycle that includes an init() method, a
doFilter() method, and a destroy() method.

Notes on Use of JSP’s

In Tomcat 5, it appears that a different compiler is being used for the Servlet engine than what we are running as
part of the

Java IDE. Hence, the error messages that come out are different.


It is critical to use an IDE that compiles JSP’s, in order to get the error messages at compile time, and their line
numbers.


To review the code generated for the servlets, you must go in
to the Tomcat ‘work’ directory, and then into the
‘org.apache’ subdirectories.


The line numbers that are reported in run
-
time error messages from Tomcat’s jvm may be off by 1
-
2 lines from what
appears in the source code in the work subdirectories.


Tomcat

5 is much more picky about requiring that the jsp:use
-
bean tag actually refers to a bean. This means that the
class must have a default constructor, and not be abstract. Breaking these rules will produce a run
-
time error. For
abstract classes, you must

change the use
-
bean tag into a Java scriptlet that fetches the information from the request
object.


Watch out for using a variable called “org”. We noticed that if you have such a variable, the generated servlet for
your JSP will not compile, because it

will contain identifiers such as “org.apache”, and with “org” also declared as a
variable, this will create a compile error. For that matter, you must also avoid variables such as “page” and
“request”.

Debugging of a Tomcat A
pplication

See

http://jakarta.apache.org/tomcat/faq/development.html#rd


Add the following options when the JVM is started:


-
Xdebug
-
Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

There are a

number of ways you can do this depending on how you normally start Tomcat:

Page
10

of
10



Set environment variables
JPDA_ADDRESS=8000

and
JPDA_TRANSPORT=dt_socket
and then
start Tomcat using
catalina jpda start
.



Set the Tomcat start
-
up icon to refer to:


C:
\
java.exe
-
Xdebug
-
Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
-

Djava.endorsed.dirs="C:
\
tomcat5.5.15
\
common
\
endorsed" "C:
\
tomcat5.5.15
\
bin
\
bootstrap.jar" start




Change the Tomcat startup.bat script (in the /bin directory) to include the following:


set JPDA_ADDRESS=8000

set JPDA_TRANSPORT=dt_socket


call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%



With Tomcat started this way (I have used approach 3 in the above list), a remote debugging option available in
Eclipse that attaches to the process. You
need to create a Debug target setting for the project, which will connect to
Tomcat. Then choose Debug As.
.
. and select that target. At this point Eclipse tries to connect to Tomcat. If the
Tomcat configuration is invalid, you will get an error message.

If not, the debug perspective will open, and the
threads within Tomcat will be visible. When one of your breakpoints is hit, the viewer windows will show it.


Note that this approach works for either of the develop/deploy models that we use (one being E
clipse builds in the
webapps directory, and the other being MyEclipse deploys into the webapps directory) because what you are doing
is connecting to the Tomcat process rather than the web application.