Class Tomcat
Tomcat supports multiple styles of configuration and startup - the most common and stable is server.xml-based, implemented in org.apache.catalina.startup.Bootstrap.
This class is for use in apps that embed tomcat.
Requirements:
- all tomcat classes and possibly servlets are in the classpath. (for example all is in one big jar, or in eclipse CP, or in any other combination)
- we need one temporary directory for work files
- no config file is required. This class provides methods to use if you have a webapp with a web.xml file, but it is optional - you can use your own servlets.
There are a variety of 'add' methods to configure servlets and webapps. These methods, by default, create a simple in-memory security realm and apply it. If you need more complex security processing, you can define a subclass of this class.
This class provides a set of convenience methods for configuring web application contexts; all overloads of the
method addWebapp()
. These methods are equivalent to adding a web application to the Host's appBase
(normally the webapps directory). These methods create a Context, configure it with the equivalent of the defaults
provided by conf/web.xml
(see initWebappDefaults(String)
for details) and add the Context to a
Host. These methods do not use a global default web.xml; rather, they add a LifecycleListener
to configure
the defaults. Any WEB-INF/web.xml and META-INF/context.xml packaged with the application will be processed normally.
Normal web fragment and ServletContainerInitializer
processing will be applied.
In complex cases, you may prefer to use the ordinary Tomcat API to create webapp contexts; for example, you might
need to install a custom Loader before the call to Container.addChild(Container)
. To replicate the basic behavior
of the addWebapp
methods, you may want to call two methods of this class: noDefaultWebXmlPath()
and getDefaultWebXmlListener()
.
getDefaultWebXmlListener()
returns a LifecycleListener
that adds the standard DefaultServlet, JSP
processing, and welcome files. If you add this listener, you must prevent Tomcat from applying any standard global
web.xml with ...
noDefaultWebXmlPath()
returns a dummy pathname to configure to prevent ContextConfig
from trying to
apply a global web.xml file.
This class provides a main() and few simple CLI arguments, see setters for doc. It can be used for simple tests and demo.
- Author:
- Costin Manolache
- See Also:
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic class
Fix reload - required if reloading and using programmatic configuration.static class
Helper class for wrapping existing servlets.static class
Fix startup sequence - required if you don't use web.xml. -
Field Summary
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionaddContext
(String contextPath, String docBase) Add a context - programmatic mode, no default web.xml used.addContext
(Host host, String contextPath, String dir) addContext
(Host host, String contextPath, String contextName, String dir) static void
addDefaultMimeTypeMappings
(Context context) Add the default MIME type mappings to the provide Context.void
Add a role to a user.addServlet
(String contextPath, String servletName, String servletClass) Equivalent to <servlet><servlet-name><servlet-class>.addServlet
(String contextPath, String servletName, Servlet servlet) Add an existing Servlet to the context with no class.forName or initialisation.static Wrapper
addServlet
(Context ctx, String servletName, String servletClass) Static version ofaddServlet(String, String, String)
static Wrapper
addServlet
(Context ctx, String servletName, Servlet servlet) Static version ofaddServlet(String, String, Servlet)
.void
Add a user for the in-memory realm.This is equivalent to adding a web application to a Host's appBase (usually Tomcat's webapps directory).Copy the specified WAR file to the Host's appBase and then calladdWebapp(String, String)
with the newly copied WAR.This is equivalent to adding a web application to a Host's appBase (usually Tomcat's webapps directory).addWebapp
(Host host, String contextPath, String docBase, LifecycleListener config) This is equivalent to adding a web application to a Host's appBase (usually Tomcat's webapps directory).addWebapp
(Host host, String contextPath, String docBase, ContextConfig config) Deprecated.protected Realm
Create an in-memory realm.void
destroy()
Destroy the server.void
Enables JNDI naming which is disabled by default.Get the default http connector.Return a listener that provides the required configuration items for JSP processing.Access to the engine, for further customization.getHost()
Get the server object.Get the service object.protected URL
getWebappConfigFile
(String path, String contextName) void
init()
Initialize the server.protected void
void
initWebappDefaults
(String contextPath) Provide default configuration for a context.static void
Static version ofinitWebappDefaults(String)
.void
setAddDefaultWebXmlToWebapp
(boolean addDefaultWebXmlToWebapp) By default, when calling addWebapp() to create a Context, the settings from from the default web.xml are added to the context.void
setBaseDir
(String basedir) Tomcat needs a directory for temp files.void
setConnector
(Connector connector) void
Sets the current host - all future webapps will be added to this host.void
The the hostname of the default host, default is 'localhost'.void
setPort
(int port) Set the port for the default connector.void
setSilent
(boolean silent) Controls if the loggers will be silenced or not.void
start()
Start the server.void
stop()
Stop the server.
-
Field Details
-
server
-
port
protected int port -
hostname
-
basedir
-
defaultConnectorCreated
protected boolean defaultConnectorCreated
-
-
Constructor Details
-
Tomcat
public Tomcat()
-
-
Method Details
-
setBaseDir
Tomcat needs a directory for temp files. This should be the first method called.By default, if this method is not called, we use:
- system properties - catalina.base, catalina.home
- [user.dir]/tomcat.$PORT
TODO: disable work dir if not needed ( no jsp, etc ).
- Parameters:
basedir
- The Tomcat base folder on which all others will be derived
-
setPort
public void setPort(int port) Set the port for the default connector. Must be called before start().- Parameters:
port
- The port number
-
setHostname
The the hostname of the default host, default is 'localhost'.- Parameters:
s
- The default host name
-
addWebapp
This is equivalent to adding a web application to a Host's appBase (usually Tomcat's webapps directory). By default, the equivalent of the default web.xml will be applied to the web application (seeinitWebappDefaults(String)
). This may be prevented by callingsetAddDefaultWebXmlToWebapp(boolean)
withfalse
. AnyWEB-INF/web.xml
andMETA-INF/context.xml
packaged with the application will always be processed and normal web fragment andServletContainerInitializer
processing will always be applied.- Parameters:
contextPath
- The context mapping to use, "" for root context.docBase
- Base directory for the context, for static files. Must exist and be an absolute path.- Returns:
- the deployed context
-
addWebapp
Copy the specified WAR file to the Host's appBase and then calladdWebapp(String, String)
with the newly copied WAR. The WAR will NOT be removed from the Host's appBase when the Tomcat instance stops. Note thatExpandWar
provides utility methods that may be used to delete the WAR and/or expanded directory if required.- Parameters:
contextPath
- The context mapping to use, "" for root context.source
- The location from which the WAR should be copied- Returns:
- The deployed Context
- Throws:
IOException
- If an I/O error occurs while copying the WAR file from the specified URL to the appBase
-
addContext
Add a context - programmatic mode, no default web.xml used. This means that there is no JSP support (no JSP servlet), no default servlet and no web socket support unless explicitly enabled via the programmatic interface. There is also noServletContainerInitializer
processing and no annotation processing. If aServletContainerInitializer
is added programmatically, there will still be no scanning forHandlesTypes
matches.API calls equivalent with web.xml:
// context-param ctx.addParameter("name", "value"); // error-page ErrorPage ep = new ErrorPage(); ep.setErrorCode(500); ep.setLocation("/error.html"); ctx.addErrorPage(ep); ctx.addMimeMapping("ext", "type");
Note: If you reload the Context, all your configuration will be lost. If you need reload support, consider using a LifecycleListener to provide your configuration.
TODO: add the rest
- Parameters:
contextPath
- The context mapping to use, "" for root context.docBase
- Base directory for the context, for static files. Must exist, relative to the server home- Returns:
- the deployed context
-
addServlet
Equivalent to <servlet><servlet-name><servlet-class>.In general it is better/faster to use the method that takes a Servlet as param - this one can be used if the servlet is not commonly used, and want to avoid loading all deps. ( for example: jsp servlet ) You can customize the returned servlet, ex:
wrapper.addInitParameter("name", "value");
- Parameters:
contextPath
- Context to add Servlet toservletName
- Servlet name (used in mappings)servletClass
- The class to be used for the Servlet- Returns:
- The wrapper for the servlet
-
addServlet
Static version ofaddServlet(String, String, String)
- Parameters:
ctx
- Context to add Servlet toservletName
- Servlet name (used in mappings)servletClass
- The class to be used for the Servlet- Returns:
- The wrapper for the servlet
-
addServlet
Add an existing Servlet to the context with no class.forName or initialisation.- Parameters:
contextPath
- Context to add Servlet toservletName
- Servlet name (used in mappings)servlet
- The Servlet to add- Returns:
- The wrapper for the servlet
-
addServlet
Static version ofaddServlet(String, String, Servlet)
.- Parameters:
ctx
- Context to add Servlet toservletName
- Servlet name (used in mappings)servlet
- The Servlet to add- Returns:
- The wrapper for the servlet
-
init
Initialize the server.- Throws:
LifecycleException
- Init error
-
start
Start the server.- Throws:
LifecycleException
- Start error
-
stop
Stop the server.- Throws:
LifecycleException
- Stop error
-
destroy
Destroy the server. This object cannot be used once this method has been called.- Throws:
LifecycleException
- Destroy error
-
addUser
Add a user for the in-memory realm. All created apps use this by default, can be replaced using setRealm().- Parameters:
user
- The user namepass
- The password
-
addRole
Add a role to a user.- Parameters:
user
- The user namerole
- The role name- See Also:
-
getConnector
Get the default http connector. You can set more parameters - the port is already initialized.Alternatively, you can construct a Connector and set any params, then call addConnector(Connector)
- Returns:
- A connector object that can be customized
-
setConnector
-
getService
Get the service object. Can be used to add more connectors and few other global settings.- Returns:
- The service
-
setHost
Sets the current host - all future webapps will be added to this host. When tomcat starts, the host will be the default host.- Parameters:
host
- The current host
-
getHost
-
getEngine
Access to the engine, for further customization.- Returns:
- The engine
-
getServer
Get the server object. You can add listeners and few more customizations. JNDI is disabled by default.- Returns:
- The Server
-
addContext
- Parameters:
host
- The host in which the context will be deployedcontextPath
- The context mapping to use, "" for root context.dir
- Base directory for the context, for static files. Must exist, relative to the server home- Returns:
- the deployed context
- See Also:
-
addContext
- Parameters:
host
- The host in which the context will be deployedcontextPath
- The context mapping to use, "" for root context.contextName
- The context namedir
- Base directory for the context, for static files. Must exist, relative to the server home- Returns:
- the deployed context
- See Also:
-
addWebapp
This is equivalent to adding a web application to a Host's appBase (usually Tomcat's webapps directory). By default, the equivalent of the default web.xml will be applied to the web application (seeinitWebappDefaults(String)
). This may be prevented by callingsetAddDefaultWebXmlToWebapp(boolean)
withfalse
. AnyWEB-INF/web.xml
andMETA-INF/context.xml
packaged with the application will always be processed and normal web fragment andServletContainerInitializer
processing will always be applied.- Parameters:
host
- The host in which the context will be deployedcontextPath
- The context mapping to use, "" for root context.docBase
- Base directory for the context, for static files. Must exist and be an absolute path.- Returns:
- the deployed context
-
addWebapp
@Deprecated public Context addWebapp(Host host, String contextPath, String docBase, ContextConfig config) Deprecated.- Parameters:
host
- The host in which the context will be deployedcontextPath
- The context mapping to use, "" for root context.docBase
- Base directory for the context, for static files. Must exist, relative to the server homeconfig
- Custom context configurator helper- Returns:
- the deployed context
- See Also:
-
addWebapp
This is equivalent to adding a web application to a Host's appBase (usually Tomcat's webapps directory). By default, the equivalent of the default web.xml will be applied to the web application (seeinitWebappDefaults(String)
). This may be prevented by callingsetAddDefaultWebXmlToWebapp(boolean)
withfalse
. AnyWEB-INF/web.xml
andMETA-INF/context.xml
packaged with the application will always be processed and normal web fragment andServletContainerInitializer
processing will always be applied.- Parameters:
host
- The host in which the context will be deployedcontextPath
- The context mapping to use, "" for root context.docBase
- Base directory for the context, for static files. Must exist and be an absolute path.config
- Custom context configuration helper. Any configuration will be in addition to equivalent of the default web.xml configuration described above.- Returns:
- the deployed context
-
getDefaultWebXmlListener
Return a listener that provides the required configuration items for JSP processing. From the standard Tomcat global web.xml. Pass this toLifecycle.addLifecycleListener(LifecycleListener)
and then pass the result ofnoDefaultWebXmlPath()
toContextConfig.setDefaultWebXml(String)
.- Returns:
- a listener object that configures default JSP processing.
-
noDefaultWebXmlPath
- Returns:
- a pathname to pass to
ContextConfig.setDefaultWebXml(String)
when usinggetDefaultWebXmlListener()
.
-
createDefaultRealm
Create an in-memory realm. You can replace it for contexts with a real one. The Realm created here will be added to the Engine by default and may be replaced at the Engine level or over-ridden (as per normal Tomcat behaviour) at the Host or Context level.- Returns:
- a realm instance
-
initBaseDir
protected void initBaseDir() -
setSilent
public void setSilent(boolean silent) Controls if the loggers will be silenced or not.- Parameters:
silent
-true
sets the log level to WARN for the loggers that log information on Tomcat start up. This prevents the usual startup information being logged.false
sets the log level to the default level of INFO.
-
setAddDefaultWebXmlToWebapp
public void setAddDefaultWebXmlToWebapp(boolean addDefaultWebXmlToWebapp) By default, when calling addWebapp() to create a Context, the settings from from the default web.xml are added to the context. Calling this method with afalse
value prior to calling addWebapp() allows to opt out of the default settings. In that event you will need to add the configurations yourself, either programmatically or by using web.xml deployment descriptors.- Parameters:
addDefaultWebXmlToWebapp
-false
will prevent the class from automatically adding the default settings when calling addWebapp().true
will add the default settings and is the default behavior.- See Also:
-
enableNaming
public void enableNaming()Enables JNDI naming which is disabled by default. Server must implementLifecycle
in order for theNamingContextListener
to be used. -
initWebappDefaults
Provide default configuration for a context. This is broadly the programmatic equivalent of the default web.xml and provides the following features:- Default servlet mapped to "/"
- JSP servlet mapped to "*.jsp" and ""*.jspx"
- Session timeout of 30 minutes
- MIME mappings (subset of those in conf/web.xml)
- Welcome files
- Parameters:
contextPath
- The path of the context to set the defaults for
-
initWebappDefaults
Static version ofinitWebappDefaults(String)
.- Parameters:
ctx
- The context to set the defaults for
-
addDefaultMimeTypeMappings
Add the default MIME type mappings to the provide Context.- Parameters:
context
- The web application to which the default MIME type mappings should be added.
-
getWebappConfigFile
-
addWebapp(Host, String, String, LifecycleListener)
instead