Apache Tomcat » Ides » I/O
Total Page:16
File Type:pdf, Size:1020Kb
212 BROUGHT TO YOU BY: join the tribe » Installation » Configuration » Logging » Clustering Apache Tomcat » IDEs » I/O... and more! By Alex Soto Bueno and Romain Manni-Bucau CONTENTS ABOUT APACHE TOMCAT Stops server waiting up to 5 seconds Visit DZone.com/refcardz stop [-force] Apache Tomcat is a pure Java open-source web server that -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 jpda start share. (often just a port) and JPDA_ SUSPEND to suspend execution immediately after start-up INSTALLATION Get More Refcardz! Get More Refcardz! 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 TOMCAT VERSION SPECIFICATION DIRECTORY DESCRIPTION Servlet 3.1 / JSP 2.3 / EL 3.0 / Tomcat 8.0.x WebSocket 1.1 / Java 7 and later Stores executable files for /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 and later /lib applications. By default, only Tomcat 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. $ wget http://repo.maven.apache.org/maven2/org/apache/ Deploys .war files or exploded web /webapps tomcat/tomcat/8.0.24/tomcat-8.0.24.tar.gz applications. $ tar -zxvf apache-tomcat-8.0.24.tar.gz $ cd apache-tomcat-8.0.24 Stores intermediate files (such as /work compiled JSP files) during its work. The root directory is known as CATALINA_HOME. Optionally, Tomcat may be configured for multiple instances by defining CATALINA_BASE for each instance. For a single installation, CATALINA_BASE is the same as CATALINA_HOME. RUNNING The main script to start Tomcat is ${CATALINA_HOME}/bin/ catalina.sh and the most used start-up commands are: COMMAND DESCRIPTION debug [-security] Starts in a debugger Starts in a separate window (or in the start [-security] background) Starts in the current window (in the run [-security] foreground) JAVA ENTERPRISEJAVA EDITION 7 APACHE TOMCAT APACHE © DZONE, INC. | DZONE.COM 2 APACHE TOMCAT CLASSLOADING CONFIGURATION bootstrap Apache Tomcat’s main configuration is composed of four files: $JAVA HOME jre lib ext ( _ / / / ) 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"> <Listener className="xxxxx" /> Common <GlobalNamingResources> <Resource name="UserDatabase" auth="Container" (lib/*.jar) type="org.apache.catalina.UserDatabase" description="User database" factory="org. apache.catalina.users.MemoryUserDatabaseFactory" pathname="conf/tomcat-users.xml" /> </GlobalNamingResources> webapp1 webapp2 <Service name="Catalina"> <Executor name="tomcatThreadPool" namePrefix="catalina- In the case of web applications, and according to Servlet exec-" maxThreads="150" minSpareThreads="4"/> specifications, when a classloader is asked to load a class or resource, it will first try in its own classloader, and then in its parent <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" classloader(s). redirectPort="8443" /> EMBEDDING <Engine name="Catalina" defaultHost="localhost"> <Real m cla s sN a m e="..." /> An embedded Tomcat instance can be started within the same JVM <Host name="localhost" appBase="webapps" of the running application. Some dependencies must be added to a unpackWARs="true" autoDeploy="true"> class path. <Valve cla s sN a m e="..." /> </Host> Gradle file with dependencies required: </Engine> </Service> dependencies { </Server> //Minimal dependencies compile 'org.apache.tomcat.embed:tomcat-embed-core:8.0.9' The XML file represents almost a 1:1 layout of the server itself, compile 'org.apache.tomcat.embed:tomcat-embed-logging- which conforms with Tomcat’s hierarchical design. juli:8.0.9' //Optional dependency for JSP Tomcat’s Digester processes the XML files and allows for instances compile 'org.apache.tomcat.embed:tomcat-embed- jasper:8.0.9' of any Java type to be added to the XML and configured in a very compile 'org.eclipse.jdt.core.compiler:ecj:4.4' Spring-like fashion. Each node can get an attribute className to } specify which implementation you want to use, as well as a set of attributes which will be set on the created instance. Then you can instantiate a new Tomcat instance as any other Java class and call Tomcat operations such as registering Servlet, setting These are the most important tags to know to use Tomcat: a webapp directory, or configuring resources programmatically. NAME ROLE //create a Tomcat instance to 8080 port Tomcat tomcat = new Tomcat(); The server (aggregate instance) and tomcat.setPort(8080); Server admin configuration (mainly shutdown //adds a new context pointing to current directory as base socket definition) and hierarchy d ir. Tomcat internal events listener (see Context ctx = tomcat.addContext("/", new File("."). Listener getAbsolutePath()); org.apache.catalina.LifecycleListener) Defines a set of container-wide resources //registers a servlet with name hello GlobalNamingResources Tomcat.addServlet(ctx, "hello", new HttpServlet() { (as opposed to application ones) protected void service(HttpServletRequest req, HttpServletResponse resp) throws Exception { Resource Defines a JNDI resource Writer w = resp.getWriter(); w.write("Hello World"); Service A set of connectors and an engine w.flush(); } Defines a protocol to use and its }); Connector configuration (most common ones are HTTP and AJP) //adds a new mapping so any URL executes hello servlet c t x.a d d S er vle t M a p pin g("/*", "h ello"); The “processor” of an incoming //starts Tomcat instance request from a connector (a pipeline tomcat.start(); Engine starting from the host, going through //waits current thread indefinitely authentication if needed, the webapp tomcat.getServer().await(); and finally the servlet) © DZONE, INC. | DZONE.COM 3 APACHE TOMCAT NAME ROLE NAME ROLE The thread pool associated with a Which paths should be scanned/ Executor Service to handle the request JarScanFilter ignored, should tag libraries (TLDs) be scanned Security repository (login/password/ Realm roles), 0 or 1 can be linked to Host, Named values that will be made Engine, and/or Context Environment visible to the web application as environment entry resources Virtual host representation (“domain”). Host It is a container of Contexts (explicit or WEB.XML implicit using appBase). This section does not refer to WEB-INF/web.xml, which is a Context A web application standard deployment descriptor of the Servlet specification, but An element of the request pipeline (can about ${CATALINA_BASE}/conf/web.xml. Valve be added on Engine, Host, or Context) This is a standard web.xml where mime types, default servlets/ filters, default welcome files, and default session timeouts are CONTEXT.XML defined. This configuration is inherited by all web applications. context.xml is a configuration file for a web application. You can Here are the default servlets and some examples of why you might also use a Context element under the Host tag in server.xml, but it need to update them: is recommended (if necessary) that you provide them either in the web application in META-INF/context.xml or (if the configuration is SERVLET GOAL local to the Tomcat instance) in ${CATALINA_BASE}/conf/<engine name>/<hostname>/<warname>.xml. Serves static resources. Default This last option overrides the META-INF file if both exist. This Encoding, is listing folder allowed are is convenient for overriding a packaged version, for instance configurable. overriding a DataSource. Serves (and compiles if needed) JSP. A shared web application configuration (across all applications) JSP Compiling information, should JSP be is done in ${CATALINA_BASE}/conf/context.xml (global) and watched for updates (development), ${CATALINA_BASE}/conf/<engine name>/<hostname>/context. and pooling are configurable. xml.default (specific to a host). Supports server side includes on SSL (exists as filter too) The following are the main children tags of Context: HTML pages; disabled by default. Can execute an external binary to NAME ROLE CGI acquire content; disabled by default. Internal events listener specific to InstanceListener filters/servlets LOGGING Tomcat internal events listener (see Listener org.apache.catalina.LifecycleListener) Tomcat uses an enhanced version of the Java Util Logging (JUL) API for “Context scoped” built into