Professional Documents
Culture Documents
Apache Tomcat
Get More Refcardz! Visit DZone.com/refcardz
Installation
C O NT E NT S Configuration
Logging
Clustering
IDEs
I/O... and more!
By Alex Soto Bueno and Romain Manni-Bucau
Apache Tomcat is a pure Java open-source web server that stop [-force]
-force option kills the process if not
implements the Java Servlet, JavaServer Pages, and Expression stopped after 5 seconds
Language specifications.
Starts under JPDA debugger
According to the JRebel report, Tomcat is one of the most used Environment variable JPDA_
web servers in the Java world with more than 50% of the market ADDRESS defines the debug address
share. jpda start
(often just a port) and JPDA_
SUSPEND to suspend execution
immediately after start-up
I N S TA L L AT I O N
When Tomcat is started in the foreground, it can be stopped by
DOWNLOAD pressing Ctrl+C.
The quickest way to run Tomcat is to download and run a
compiled version. Go to http://tomcat.apache.org/ and in the There is a Windows package distribution that installs Tomcat
Download section choose the Tomcat version that fits your as a Service on Windows operating systems. Most Linux
requirements and package file depending on your OS. distributions have their own packaging.
DIRECTORY LAYOUT
TOMC AT VERSION SPECIFIC ATION
DIRECTORY DESCRIPTION
Servlet 3.1 / JSP 2.3 / EL 3.0 /
Tomcat 8.0.x Stores executable files for
WebSocket 1.1 / Java 7 and later
/bin Windows/*nix systems to start and
Servlet 3.0 / JSP 2.2 / EL 2.2 / stop server.
Tomcat 7.0.x WebSocket 1.1 / Java 6 and later
(WebSocket requires Java 7) /conf Stores configuration files.
Servlet 2.5 / JSP 2.1 / EL 2.1 / Java 5 Stores libraries to share between all
Tomcat 6.0.x /lib applications. By default, only Tomcat
and later
libraries are in this directory.
To run Tomcat, you have to first install a Java Runtime
Environment (JRE). Make sure to install the right version /logs Stores Tomcat log files.
depending on the Tomcat version you want to run (see table Stores temporary files created using
/temp
above). the Java File API.
RUNNING
The main script to start Tomcat is ${CATALINA_HOME}/bin/
catalina.sh and the most used start-up commands are:
CLASSLOADING
CO N F I G U R AT I O N
bootstrap
($JAVA_HOME/jre/lib/ext) Apache Tomcats main configuration is composed of four files:
server.xml, context.xml, web.xml, and logging.properties.
SERVER.XML
server.xml is located in ${CATALINA_BASE}/conf and represents
system the server itself. Here is an example:
(bin/boostrap.jar:bin/tomcat-juli.jar)
<?xml version='1.0' encoding='utf-8'?>
<Server port="8005" shutdown="SHUTDOWN">
D Z O NE, INC . | DZ O NE .C O M
3 APACHE TOMCAT
D Z O NE, INC . | DZ O NE .C O M
4 APACHE TOMCAT
DYNAMIC VALUES
IDES
You can use place holders like ${xxx}. They get replaced
automatically at runtime with the value of the Java system property Apache Tomcat is supported by major IDE vendors.
with the key xxx.
ECLIPSE
ROOT LOGGER To register Tomcat on Eclipse WTP (Web Tools Platform).
Root logger is configured using an empty name:
Open Window -> Preferences -> Server -> Installed Runtimes
.handlers = . Click on Add and in New Server Runtime, select Apache ->
HANDLER Apache Tomcat v8.0
Tomcat provides several additional handlers like org.apache.juli. Click Next and fill in your Tomcat installation directory
FileHandler, which supports log buffering; AsyncFileHandler, which is
asynchronous; and some formatters like JdkLoggerFormatter, which INTELLIJ IDEA
uses the log4j equivalent format %r %-15.15c{2} %-1.1p %m %n. To register Tomcat in IntelliJ IDEA Ultimate Edition (communtiy
edition is not supported):
SERVLETCONTEXT LOGGING
ServletContext.log(...) output is configurable using property Open File -> Settings -> (IDE Settings) Application Servers
Here is the most basic example: The main difference between NIO and BIO is that with the BIO
connector you generally need more threads to handle requests
<Cluster className="org.apache.catalina.ha.tcp. concurrently, and they dont guarantee better performances. These
SimpleTcpCluster"/>
connectors impose you to get one thread by connection!
D Z O NE, INC . | DZ O NE .C O M
5 APACHE TOMCAT
AJP JNDI
AJP is a protocol like HTTP. Its main goal is to get higher Tomcat provides a JNDI InitialContext implementation instance for
performances. It is a binary version of HTTP, and also a connected each web application. As mentioned in the Configuration section,
protocol as opposed to HTTP. It can be used with httpd (a.k.a Apache JNDI resources can be registered in conf/server.xml, conf/web.xml,
Web Server) and most of the time with mod_jk or mod_proxy_ajp or any context.xml file. But Tomcat also follows the Java EE standard
httpd modules. If you are using SSL or have a lot of static resources, for /WEB-INF/web.xml file to reference/define resources.
this is the fastest connector! In order to use a JNDI resource, specify the JNDI name defined in the
COMETD web applications deployment descriptor:
CometD is the old way to handle asynchronous I/O (i.e. let the context.xml
container call you when data are available). This only works with <context ...>
APR or NIO connectors. <!-- Definition of DataSource in context.xml -->
<Resource name="jdbc/employeeDB" type="javax.sql.
To use CometD, you first need to implement it within a servlet org. DataSource" global="jdbc/employeeDB" .../>
</context>
apache.catalina.comet.CometProcessor (eliminating portability) web.xml
and then handle events in event(CometEvent): <web-app>
<!-- Declaring a reference to DataSource in web.xml -->
public class MyCometDServlet extends HttpServlet <resource-ref>
implements CometProcessor { <description>Employee Datasource</description>
@Override <res-ref-name>jdbc/employeeDB</res-ref-name>
public void event(final CometEvent event) <res-type>javax.sql.DataSource</res-type>
throws IOException, ServletException { <res-auth>Container</res-auth>
</resource-ref>
final HttpServletRequest request = event. <env-entry>
getHttpServletRequest(); <env-entry-name>message</env-entry-name>
final HttpServletResponse response = event. <env-entry-value>Hello World</env-entry-value>
getHttpServletResponse(); <env-entry-type>java.lang.String</env-entry-type>
</env-entry>
if (event.getEventType() == CometEvent.EventType.BEGIN) </webapp>
{ //keep the response to bulk send data to everybody
} else
if (event.getEventType() == CometEvent.EventType.
Java Code
ERROR || event.getEventType() == CometEvent.EventType.END)
{ Context initCtx = new InitialContext();
// state cleanup if needed DataSource ds = (DataSource) initCtx.lookup("java:comp/env/
event.close(); jdbc/EmployeeDB");
// we are done String message = (String)initCtx.lookup("java:comp/env/
} else message");
if (event.getEventType() == CometEvent.EventType.READ)
{
final InputStream is = request.getInputStream(); T O M C AT L I S T E N E R S
do {
// read is
} while (is.available() > 0); A Listener element defines a component that performs actions when
} specific events occur, usually Tomcat starting or Tomcat stopping.
}
Listeners are registered inside conf/server.xml inside Server, Engine,
WEBSOCKET Host, and Context tags.
WebSockets (RFC 6455) have been supported by Tomcat since Each Listener must implement org.apache.catalina.LifecycleListener
version 7, but only versions 7.0.43 and later implement the interface.
specification (a.k.a JSR-356). Before ( version 7.0.27 and earlier)
Tomcat was using a proprietary API and implementation didnt scale CUSTOM LISTENER
as much as today -- so ensure you are using an up-to-date version. public class PrintLifecycleStatesListener implements
LifecycleListener {
The Tomcat WebSocket implementation needs at least Java 7. If you @Override
are running on Java 7, it is activated by default and you just need to public void lifecycleEvent(LifecycleEvent e) {
deploy your code inside Tomcat: System.out.println(e.getLifecycle().getStateName());
}
}
@ServerEndpoint(/tchat)
public class TchatEndpoint {
The JAR file containing this class is stored at $CATALINA_BASE/lib
@OnMessage
directory.
public void onMessage(Session session, String msg) {
try {
Add the next line at conf/server.xml.
session.getBasicRemote().sendText(msg);
} catch (IOException e) { ... }
} <Server ...>
} <Listener className="org.superbiz.
PrintLifecycleStatesListener"/>
</Server>
WebSocket doesnt require you to use an APR or NIO connector like
CometD does, but it is highly recommended, as you will likely have a
high number of connections.
D Z O NE, INC . | DZ O NE .C O M
6 APACHE TOMCAT
Fixes the ports used by Arquillian Tomcat 8 adapter release is coming soon.
org.apache.catalina.mbeans.
the JMX/RMI Server; not Maven coordinates can be found at:
JmxRemoteLifecycleListener
enabled by default.
http://arquillian.org/modules/arquillian-tomcat-embedded-7-
container-adapter/
D E P LOY I N G
http://arquillian.org/modules/arquillian-tomcat-managed-7-
After installing and configuring Tomcat, you will need to deploy web container-adapter/
applications.
http://arquillian.org/modules/arquillian-tomcat-remote-7-
DROP-IN WAR
container-adapter/
Deploying an application to Tomcat can be as simple as dropping a
WAR file inside the $CATALINA_BASE/webapps directory; this will http://arquillian.org/modules/arquillian-tomcat-embedded-8-
deploy the application. container-adapter/
To enable hot deployment, the autoDeploy attribute from host tag in JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.
port=8089"
server.xml must be set to true. See the configuration section for an JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.
example. ssl=false"
JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.
authenticate=false"
D Z O NE, INC . | DZ O NE .C O M
7 APACHE TOMCAT
MAVEN
GOAL DESCRIPTION
Maven is still one of the most used build tools and therefore Tomcat
integration is available. deploy/ undeploy/ (Un)deploys a WAR
redeploy
This integration is mainly (in addition to deploying artifacts on
central) a Maven plugin. Create a runnable JAR or WAR running
Exec-war /
Tomcat and your application (java -jar
Today, there are two plugins, tomcat6-maven-plugin for Tomcat 6 standalone-war
mytomcatapp.jar)
and tomcat7-maven-plugin for Tomcat 7; tomcat8-maven-plugin
is coming soon. Start Tomcat embedded with current project
run
deployed as dynamic project
Their usage is more or less the same:
Same as run, using a WAR instead of
<plugin>
run-war
resources
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId> Stop started servers (useful if using pre-
<version>2.2</version>
shutdown integration-test phase to start Tomcat and
<configuration>
<url>http://localhost:8080/manager</url> post-integration-test to stop it)
</configuration>
</plugin> Note: Often goals will exist with the -only suffix. For example,
the deploy-only goal will not fork a Maven package lifecycle.
Here are the main configurations of the Maven plugin:
Each goal has further configurations, for example the context
PAR A M ETER GOAL path within the deploy application goal.
Tomcat Manager URL (to deploy/undeploy/ You can find more details at http://tomcat.apache.org/maven-
url
start/stop/reload) plugin-trunk/tomcat7-maven-plugin/plugin-info.html.
Use settings.xml server for authentication on
server JAVA EE AND BEYOND
the Tomcat Manager application
Tomcat is a Servlet container following Servlet/JSP/EL specification.
Encoding to use to communicate with the However, if you are required to use any other Java EE specifications
charset
Tomcat Manager application like CDI, JPA, EJB, JAX-RS, or Bean Validation, you can integrate
them yourself (assuming you understand the perils of doing it by
Username/ Credential of the manager application
yourself), or you can simply use Apache TomEE. Apache TomEE
password
(pronounced Tommy) is the Java Enterprise Edition of Apache
Once these configurations are set up, the available goals are as Tomcat (Tomcat + Java EE = TomEE) and it is certified as Java EE 6
follows: Web Profile. It maintains the lightness and simplicity of Tomcat but
with the full power of Java EE.
JOIN NOW
DZONE, INC.
150 PRESTON EXECUTIVE DR.
CARY, NC 27513
DZone communities deliver over 6 million pages each month to more than 3.3 million software 888.678.0399
developers, architects and decision makers. DZone offers something for everyone, including news, 919.678.0300
tutorials, cheat sheets, research guides, feature articles, source code and more.
REFCARDZ FEEDBACK WELCOME
"DZone is a developer's dream," says PC Magazine. refcardz@dzone.com
D Z O NE,INC
form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. |
Copyright 2015 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
DZONE, DZ OSPONSORSHIP
NE .C O M OPPORTUNITIES
. in anyINC.
sales@dzone.com VERSION 1.0 $7.95