Class Tomcat
- java.lang.Object
- 
- org.apache.catalina.startup.Tomcat
 
- 
 public class Tomcat extends java.lang.ObjectMinimal tomcat starter for embedding/unit tests.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 byconf/web.xml(seeinitWebappDefaults(String)for details) and add the Context to a Host. These methods do not use a global default web.xml; rather, they add aLifecycleListenerto configure the defaults. Any WEB-INF/web.xml and META-INF/context.xml packaged with the application will be processed normally. Normal web fragment andServletContainerInitializerprocessing 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 theaddWebappmethods, you may want to call two methods of this class:noDefaultWebXmlPath()andgetDefaultWebXmlListener().getDefaultWebXmlListener()returns aLifecycleListenerthat 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 preventContextConfigfrom 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:
- TestTomcat
 
- 
- 
Nested Class SummaryNested Classes Modifier and Type Class Description static classTomcat.DefaultWebXmlListenerFix reload - required if reloading and using programmatic configuration.static classTomcat.ExistingStandardWrapperHelper class for wrapping existing servlets.static classTomcat.FixContextListenerFix startup sequence - required if you don't use web.xml.
 - 
Constructor SummaryConstructors Constructor Description Tomcat()
 - 
Method SummaryAll Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description ContextaddContext(java.lang.String contextPath, java.lang.String docBase)Add a context - programmatic mode, no default web.xml used.ContextaddContext(Host host, java.lang.String contextPath, java.lang.String dir)ContextaddContext(Host host, java.lang.String contextPath, java.lang.String contextName, java.lang.String dir)static voidaddDefaultMimeTypeMappings(Context context)Add the default MIME type mappings to the provide Context.voidaddRole(java.lang.String user, java.lang.String role)Add a role to a user.WrapperaddServlet(java.lang.String contextPath, java.lang.String servletName, java.lang.String servletClass)Equivalent to <servlet><servlet-name><servlet-class>.WrapperaddServlet(java.lang.String contextPath, java.lang.String servletName, Servlet servlet)Add an existing Servlet to the context with no class.forName or initialisation.static WrapperaddServlet(Context ctx, java.lang.String servletName, java.lang.String servletClass)Static version ofaddServlet(String, String, String)static WrapperaddServlet(Context ctx, java.lang.String servletName, Servlet servlet)Static version ofaddServlet(String, String, Servlet).voidaddUser(java.lang.String user, java.lang.String pass)Add a user for the in-memory realm.ContextaddWebapp(java.lang.String contextPath, java.lang.String docBase)This is equivalent to adding a web application to a Host's appBase (usually Tomcat's webapps directory).ContextaddWebapp(java.lang.String contextPath, java.net.URL source)Copy the specified WAR file to the Host's appBase and then calladdWebapp(String, String)with the newly copied WAR.ContextaddWebapp(Host host, java.lang.String contextPath, java.lang.String docBase)This is equivalent to adding a web application to a Host's appBase (usually Tomcat's webapps directory).ContextaddWebapp(Host host, java.lang.String contextPath, java.lang.String docBase, LifecycleListener config)This is equivalent to adding a web application to a Host's appBase (usually Tomcat's webapps directory).protected RealmcreateDefaultRealm()Create an in-memory realm.voiddestroy()Destroy the server.voidenableNaming()Enables JNDI naming which is disabled by default.ConnectorgetConnector()Get the default HTTP connector that is used by the embedded Tomcat.LifecycleListenergetDefaultWebXmlListener()Return a listener that provides the required configuration items for JSP processing.EnginegetEngine()Access to the engine, for further customization.HostgetHost()ServergetServer()Get the server object.ServicegetService()Get the service object.protected java.net.URLgetWebappConfigFile(java.lang.String path, java.lang.String contextName)voidinit()Initialize the server.voidinit(ConfigurationSource source)Initialize the server given the specified configuration source.voidinit(ConfigurationSource source, java.lang.String[] catalinaArguments)Initialize the server given the specified configuration source.protected voidinitBaseDir()voidinitWebappDefaults(java.lang.String contextPath)Provide default configuration for a context.static voidinitWebappDefaults(Context ctx)Static version ofinitWebappDefaults(String).static voidmain(java.lang.String[] args)Main executable method for use with a Maven packager.java.lang.StringnoDefaultWebXmlPath()voidsetAddDefaultWebXmlToWebapp(boolean addDefaultWebXmlToWebapp)By default, when calling addWebapp() to create a Context, the settings from from the default web.xml are added to the context.voidsetBaseDir(java.lang.String basedir)Tomcat requires that the base directory is set because the defaults for a number of other locations, such as the work directory, are derived from the base directory.voidsetConnector(Connector connector)Set the specified connector in the service, if it is not already present.voidsetHost(Host host)Sets the current host - all future webapps will be added to this host.voidsetHostname(java.lang.String s)The the hostname of the default host, default is 'localhost'.voidsetPort(int port)Set the port for the default connector.voidsetSilent(boolean silent)Controls if the loggers will be silenced or not.voidstart()Start the server.voidstop()Stop the server.
 
- 
- 
- 
Field Detail- 
serverprotected Server server 
 - 
portprotected int port 
 - 
hostnameprotected java.lang.String hostname 
 - 
basedirprotected java.lang.String basedir 
 
- 
 - 
Method Detail- 
setBaseDirpublic void setBaseDir(java.lang.String basedir) Tomcat requires that the base directory is set because the defaults for a number of other locations, such as the work directory, are derived from the base directory. This should be the first method called.If this method is not called then Tomcat will attempt to use these locations in the following order: - if set, the catalina.base system property
- if set, the catalina.home system property
- The user.dir system property (the directory where Java was run from)
      where a directory named tomcat.$PORT will be created. $PORT is the
      value configured via setPort(int)which defaults to 8080 if not set
 TODO: disable work dir if not needed ( no jsp, etc ). - Parameters:
- basedir- The Tomcat base folder on which all others will be derived
 
 - 
setPortpublic void setPort(int port) Set the port for the default connector. The default connector will only be created if getConnector is called.- Parameters:
- port- The port number
 
 - 
setHostnamepublic void setHostname(java.lang.String s) The the hostname of the default host, default is 'localhost'.- Parameters:
- s- The default host name
 
 - 
addWebapppublic Context addWebapp(java.lang.String contextPath, java.lang.String docBase) 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.xmlandMETA-INF/context.xmlpackaged with the application will always be processed and normal web fragment andServletContainerInitializerprocessing 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
 
 - 
addWebapppublic Context addWebapp(java.lang.String contextPath, java.net.URL source) throws java.io.IOException 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 thatExpandWarprovides 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:
- java.io.IOException- If an I/O error occurs while copying the WAR file from the specified URL to the appBase
 
 - 
addContextpublic Context addContext(java.lang.String contextPath, java.lang.String docBase) 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 noServletContainerInitializerprocessing and no annotation processing. If aServletContainerInitializeris added programmatically, there will still be no scanning forHandlesTypesmatches.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
 
 - 
addServletpublic Wrapper addServlet(java.lang.String contextPath, java.lang.String servletName, java.lang.String servletClass) 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 to
- servletName- Servlet name (used in mappings)
- servletClass- The class to be used for the Servlet
- Returns:
- The wrapper for the servlet
 
 - 
addServletpublic static Wrapper addServlet(Context ctx, java.lang.String servletName, java.lang.String servletClass) Static version ofaddServlet(String, String, String)- Parameters:
- ctx- Context to add Servlet to
- servletName- Servlet name (used in mappings)
- servletClass- The class to be used for the Servlet
- Returns:
- The wrapper for the servlet
 
 - 
addServletpublic Wrapper addServlet(java.lang.String contextPath, java.lang.String servletName, Servlet servlet) Add an existing Servlet to the context with no class.forName or initialisation.- Parameters:
- contextPath- Context to add Servlet to
- servletName- Servlet name (used in mappings)
- servlet- The Servlet to add
- Returns:
- The wrapper for the servlet
 
 - 
addServletpublic static Wrapper addServlet(Context ctx, java.lang.String servletName, Servlet servlet) Static version ofaddServlet(String, String, Servlet).- Parameters:
- ctx- Context to add Servlet to
- servletName- Servlet name (used in mappings)
- servlet- The Servlet to add
- Returns:
- The wrapper for the servlet
 
 - 
initpublic void init(ConfigurationSource source) Initialize the server given the specified configuration source. The server will be loaded according to the Tomcat configuration files contained in the source (server.xml, web.xml, context.xml, SSL certificates, etc). If no configuration source is specified, it will use the default locations for these files.- Parameters:
- source- The configuration source
 
 - 
initpublic void init(ConfigurationSource source, java.lang.String[] catalinaArguments) Initialize the server given the specified configuration source. The server will be loaded according to the Tomcat configuration files contained in the source (server.xml, web.xml, context.xml, SSL certificates, etc). If no configuration source is specified, it will use the default locations for these files.- Parameters:
- source- The configuration source
- catalinaArguments- The arguments that should be passed to Catalina
 
 - 
initpublic void init() throws LifecycleExceptionInitialize the server.- Throws:
- LifecycleException- Init error
 
 - 
startpublic void start() throws LifecycleExceptionStart the server.- Throws:
- LifecycleException- Start error
 
 - 
stoppublic void stop() throws LifecycleExceptionStop the server.- Throws:
- LifecycleException- Stop error
 
 - 
destroypublic void destroy() throws LifecycleExceptionDestroy the server. This object cannot be used once this method has been called.- Throws:
- LifecycleException- Destroy error
 
 - 
addUserpublic void addUser(java.lang.String user, java.lang.String pass)Add a user for the in-memory realm. All created apps use this by default, can be replaced using setRealm().- Parameters:
- user- The user name
- pass- The password
 
 - 
addRolepublic void addRole(java.lang.String user, java.lang.String role)Add a role to a user.- Parameters:
- user- The user name
- role- The role name
- See Also:
- addUser(String, String)
 
 - 
getConnectorpublic Connector getConnector() Get the default HTTP connector that is used by the embedded Tomcat. It is first configured connector in the service. If there's no connector defined, it will create and add a default connector using the port and address specified in this Tomcat instance, and return it for further customization.- Returns:
- The connector object
 
 - 
setConnectorpublic void setConnector(Connector connector) Set the specified connector in the service, if it is not already present.- Parameters:
- connector- The connector instance to add
 
 - 
getServicepublic Service getService() Get the service object. Can be used to add more connectors and few other global settings.- Returns:
- The service
 
 - 
setHostpublic void setHost(Host host) 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
 
 - 
getHostpublic Host getHost() 
 - 
getEnginepublic Engine getEngine() Access to the engine, for further customization.- Returns:
- The engine
 
 - 
getServerpublic Server getServer() Get the server object. You can add listeners and few more customizations. JNDI is disabled by default.- Returns:
- The Server
 
 - 
addContextpublic Context addContext(Host host, java.lang.String contextPath, java.lang.String dir) - Parameters:
- host- The host in which the context will be deployed
- contextPath- 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(String, String)
 
 - 
addContextpublic Context addContext(Host host, java.lang.String contextPath, java.lang.String contextName, java.lang.String dir) - Parameters:
- host- The host in which the context will be deployed
- contextPath- The context mapping to use, "" for root context.
- contextName- The context name
- dir- Base directory for the context, for static files. Must exist, relative to the server home
- Returns:
- the deployed context
- See Also:
- addContext(String, String)
 
 - 
addWebapppublic Context addWebapp(Host host, java.lang.String contextPath, java.lang.String docBase) 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.xmlandMETA-INF/context.xmlpackaged with the application will always be processed and normal web fragment andServletContainerInitializerprocessing will always be applied.- Parameters:
- host- The host in which the context will be deployed
- 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
 
 - 
addWebapppublic Context addWebapp(Host host, java.lang.String contextPath, java.lang.String docBase, LifecycleListener config) 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.xmlandMETA-INF/context.xmlpackaged with the application will always be processed and normal web fragment andServletContainerInitializerprocessing will always be applied.- Parameters:
- host- The host in which the context will be deployed
- 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.
- 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
 
 - 
getDefaultWebXmlListenerpublic LifecycleListener 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.
 
 - 
noDefaultWebXmlPathpublic java.lang.String noDefaultWebXmlPath() - Returns:
- a pathname to pass to
 ContextConfig.setDefaultWebXml(String)when usinggetDefaultWebXmlListener().
 
 - 
createDefaultRealmprotected Realm 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
 
 - 
initBaseDirprotected void initBaseDir() 
 - 
setSilentpublic void setSilent(boolean silent) Controls if the loggers will be silenced or not.- Parameters:
- silent-- truesets the log level to WARN for the loggers that log information on Tomcat start up. This prevents the usual startup information being logged.- falsesets the log level to the default level of INFO.
 
 - 
setAddDefaultWebXmlToWebapppublic 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 afalsevalue 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-- falsewill prevent the class from automatically adding the default settings when calling addWebapp().- truewill add the default settings and is the default behavior.
- See Also:
- addWebapp(Host, String, String, LifecycleListener)
 
 - 
enableNamingpublic void enableNaming() Enables JNDI naming which is disabled by default. Server must implementLifecyclein order for theNamingContextListenerto be used.
 - 
initWebappDefaultspublic void initWebappDefaults(java.lang.String contextPath) 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
 
 - 
initWebappDefaultspublic static void initWebappDefaults(Context ctx) Static version ofinitWebappDefaults(String).- Parameters:
- ctx- The context to set the defaults for
 
 - 
addDefaultMimeTypeMappingspublic static void addDefaultMimeTypeMappings(Context context) 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.
 
 - 
getWebappConfigFileprotected java.net.URL getWebappConfigFile(java.lang.String path, java.lang.String contextName)
 - 
mainpublic static void main(java.lang.String[] args) throws java.lang.ExceptionMain executable method for use with a Maven packager.- Parameters:
- args- the command line arguments
- Throws:
- java.lang.Exception- if an error occurs
 
 
- 
 
-