TomCat Tutorial

Advertisement

Advertisement

Overview

Introduction

TomCat, in its simplest concept, is a web server. Well, it's more than that. While it can serve static files, its primary purpose is to act as a 'servlet container' that serves Java web applications. It can process [.jsp] files, which are like PHP scripts but for Java, and it can also run [Java Servlets], which are classes that process the GET, POST, and other HTTP requests. TomCat will listen on TCP ports for HTTP requests, and route requests to your Java classes, JSP files, or static files. It is also possible to embed TomCat in to a standalone application, but that is out of the scope of this document.

Beginner level Java knowledge is expected, although there is virtually no Java code in this tutorial specfically. This will cover basic installation, configuration, and admin aspects. This is aimed at beginner to intermediate developers who want to learn about basic Java web app hosting. You should either be a system administrator setting up TomCat or a developer learning how to set up TomCat.

I would always recommend using the official documentation at http://tomcat.apache.org/ for the latest and most accurate information. This is meant as a quick start guide that includes the things I think are important to know to get started. There are a number of features that are not covered here. For example, TomCat can be embedded inside your application.

One popular alternative to TomCat is Eclipse Jetty. It is often used when you need a lightweight embedded servlet container. Servlet containers like TomCat and Jetty only support a subset of JavaEE specifications (JSP and servlets). You can use any full JavaEE server as an alternative since they will support servlets and JSP, but they will also support a lot more like Enterprise Java Beans (EJB), Java Persistence API (JPA), and other things. TomCatEE and Glassfish are examples of full EE servers.

Setup

Get Java

If you don't already have a copy of Java, you will need a copy of the Java Runtime Environment (JRE) at a minimum. I recommended getting the full Java Development Kit (JDK), which includes the JRE. If you want to develop your own apps you must get the JDK. If you only want to run TomCat then you only need the JRE.

For information on installing multiple JDK versions on Windows, check out my Install multiple JDK in Windows for Java Development tutorial.

Steps:

  • Download Java JDK. I am using OpenJDK 11 in this example.
  • Extract zip file
  • Move Java to wherever you want. Could be your home directory, or /opt/openjdk11 for example. For the rest of this example we will assume the path /opt/openjdk11 or C:\opt\openjdk11 is used
  • Set the JAVA_HOME environment variable for TomCat. If you are only downloading the JRE and not the full JDK, set JRE_HOME.

Optional: In Linux, storing and running the JDK from your home directory works just fine for personal development, but if you are the system administrator and you want to make Java available for everyone you can move it to a location that everyone can read.

# Move Java to a system location (Linux)
sudo chown -R root:root /opt/openjdk11
chmod -R 775 /opt/openjdk11

Optional: Adding Java executables to your PATH, allowing it to be called from the command line. This is not required if you are setting up TomCat as a service, but is useful you want to use Java and the compiler from the shell to run programs and do development. Add the bin directory inside JAVA_HOME to your path. For example /opt/openjdk11/bin to your PATH.

# Windows update PATH permanently
setx PATH=C:\opt\openjdk11\bin;%PATH%

# Linux
export PATH=/opt/openjdk11/bin:$PATH

Get TomCat

First, download TomCat from http://tomcat.apache.org/. Extract the file after downloading. If you are using an IDE for development like NetBeans or IntelliJ, you just need to configure your IDE to use the TomCat directory and it will take care of starting and stopping the service as well as deploying your app.

There are two important environment variables to set before running:

  • Set CATALINA_HOME to the root of your TomCat directory.
  • Set JAVA_HOME to the root directory of your Java JDK or JRE.

There are a few ways to use TomCat:

  • Manually starting and stopping TomCat process using startup.sh and shutdown.sh
  • Configuring your IDE to manage the TomCat instance for you (for development)
  • Set up TomCat as a system service (for production)
  • Embedding TomCat in your application (not covered here)

Important directories inside the TomCat directory:

  • conf/ - Contains configuration files
  • logs/ - Log files for web apps
  • webapps/ - Directory to store web apps directories and .war files
  • webapps/ROOT/ - The default web root

Install TomCat as a Windows service

To install TomCat as a Windows service, use the "Windows Service Installer" downloadable from https://tomcat.apache.org/index.html. Go to the "Download" page for the version you want and look for the download named 32-bit/64-bit Windows Service Installer. After installation, you will find it in the "Services" manager in Windows. You can start and stop it from there.

To learn more about Windows services, check the official documentation. Here is a quick link to version 9 Windows service HOW-TO.

Setup TomCat as a Linux Service (systemd)

Setting up TomCat as a service allows it to run in the background and be configured to run at boot time. If you want a TomCat server to run 24/7 and restart automatically, you want to set it up as a service. Most Linux distributions these days use systemd and that is what's covered here. This assumes you already have Java and TomCat downloaded and extracted. In this example, we assume TomCat was moved to the /opt/ directory.

Prepare low privilege user and directory permissions

This is optional, but recommended. I don't recommend running the service with the root user. I also recommend against usign your personal user, unless it is your own server for personal use and development only. I do recommend creating a low privilege user named "tomcat" to run the service.

# Create low priv tomcat user
sudo useradd tomcat

# Let scripts be executable (i.e. startup/shutdown scripts)
sudo chmod +x /opt/tomcat9/bin/*.sh

# Reset permissions on tomcat directory
sudo chmod -R 775 /opt/tomcat/webapps
sudo chown -R tomcat:tomcat /opt/tomcat9

# Optionally add your user to the tomcat group
# to write in the tomcat directory
sudo gpasswd -a myusername tomcat

Example systemd service file

This is an example of a systemd service file. For example, you can put this file in /etc/systemd/system/tomcat.service and then it will create a service named "tomcat".

# Example systemd file
[Unit]
Description=Apache Tomcat
After=network.target

[Service]
Type=forking

Environment=JAVA_HOME=/opt/openjdk11
Environment=CATALINA_PID=/opt/tomcat9/tomcat.pid
Environment=CATALINA_HOME=/opt/tomcat9
Environment=CATALINA_BASE=/opt/tomcat9
Environment='CATALINA_OPTS=-Xmx1024M -server'

WorkingDirectory=/opt/tomcat9

ExecStart=/opt/tomcat9/bin/startup.sh
ExecStop=/opt/tomcat9/bin/shutdown.sh

User=tomcat
Group=tomcat
UMask=0007
RestartSec=15
Restart=always

[Install]
WantedBy=multi-user.target

Control the systemd service

Control the service and get information using the commands below. Make sure you run the enable command so that it will start automatically on reboot.

sudo systemctl status tomcat
sudo systemctl enable tomcat # Sets it to start on boot
sudo systemctl start tomcat
sudo systemctl stop tomcat
sudo systemctl restart tomcat

Use nginx as a reverse proxy

In some situations, you can use TomCat to listen publicly on port 80 or 443, but in many cases you need to run TomCat on a server with other web services running. In those situations, it can be useful to set up a reverse proxy to listen publicly and handle routing traffic to internal web services like TomCat. I recommend nginx and I have an Nginx Tutorial if you want to learn how to do that.

Basic usage

This section covers some common tasks like starting and stopping the server, serving static files and JSPs, and modifying common settings.

Start and stop TomCat manually

In the bin\ directory, there will be a startup and shutdown script. A .sh is provided for Linux and .bat for Windows. Run the script, setting the environment variables JAVA_HOME and CATALINA_HOME if needed.

Windows example:

set JAVA_HOME=C:\opt\openjdk11
set CATALINA_HOME=C:\opt\tomcat9

C:\opt\tomcat9\bin\startup.bat
C:\opt\tomcat9\bin\shutdown.bat

Linux example:

export JAVA_HOME=/opt/openjdk11
export CATALINA_HOME=/opt/tomcat9

# Might need sudo for these
/opt/tomcat9/bin/startup.sh
/opt/tomcat9/bin/shutdown.sh

Verify TomCat server is running

Visit http://localhost:8080 to see if TomCat is working. You might need to replace localhost with the IP address of your server if it is a remote test. If you installed manually, the default port is 8080. If you used apt-get or the Windows installer, it should default to port 80. We'll cover how to change the port later in this section about modifying settings.

Serve static files

TomCat can handle serving static files out of the box. By default there is a webapps/ROOT/ directory in the TomCat's webapps/ directory. There is already an index.jsp and some other resources inside. That is the landing page you hit when you visited the TomCat server in the browser in the previous section at http://<ip>:8080

You can add more static files to the webapps/ROOT/ directory, You can create a new directory inside webapps/ directory and place static files there. accessible at /<directory_name> (e.g. http://localhost:8080/mywebapp).

You can put flat files like .txt, .zip or .html and they will be served directly. You can also create subdirectories.

Serve Java Server Pages (JSP)

Serving .jsp pages is just as easy as serving static files. You just drop in JSP files in a webapp directory like ROOT and point your client at it. There are no XML configurations or WAR files needed. Just point your browser to /yourjsp.jsp and it will run. TomCat will actually compile them and process them dynamically before returning the response to the client. They are treated like PHP scripts in that sense. They can be treated like HTML files with dynamic Java code inserted at various places. There is no need to restart the server or recompile code when making updates to .jsp pages.

Here's one simple example of a JSP if you want to test. It shows how to print out text, create new objects, and get headers from the request.

<!-- hello.jsp -->
<html>
    <body>
        <p><% out.print("Hello, world!"); %></p>
        <p>8 x 8 = <%= 8 * 8 %></p>
        <p>Time: <%= new java.util.Date() %></p>
        <p>Host requested: <%= request.getHeader("Host") %></p>
    </body>
</html>

Name it hello.jsp and drop it in the webapps/ROOT directory, and then visit https://localhost:8080/hello.jsp. Or, create a directory like hello/ inside webapps and put the file in there, then visit http://localhost:8080/hello/hello.jsp.

Modify settings

TomCat configuration files live in the conf/ directory of the root TomCat directory. The main file is server.xml and that is where you would change the listen port. Inside server.xml the main listening port is defined in a section labeled Connector. The section will look something like this:

<!-- A "Connector" represents an endpoint by which requests are received
    and responses are returned. Documentation at :
    Java HTTP Connector: /docs/config/http.html
    Java AJP  Connector: /docs/config/ajp.html
    APR (HTTP/AJP) Connector: /docs/apr.html
    Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
-->
<Connector port="8080" protocol="HTTP/1.1"
        connectionTimeout="20000"
        redirectPort="8443" >

Deploy web apps

Deploying web apps can be done in a number of ways which are listed below.

  • Manually copying the web app directory to the TomCat's webapps/ directory
  • Placing a .war file in the webapps/ directory
  • Using Maven plugin to deploy
  • Using the web app named manager that comes packaged with TomCat

The TomCat manager web app is described further down in the manage web apps section.

Use the admin web interface

There are two web apps that come bundled with TomCat to help with administration.

One is the Virtual Host Manager which lets you listen for multiple different domains. This can be accessed at /host-manager/html and requires certain roles to access (explained below).

The other web app that comes bundled with TomCat is the Web Application Manager. This one is used more often and is more relevant to beginners. This one can be accessed at /manager/html. This one lists al the web apps that are available and which ones are running. You can start, start, deploy, undeploy, and expire sessions. It is quite useful.

Create a TomCat admin user

You can add users to TomCat in the conf/tomcat-users.xml file. There will be a section in the xml labeled tomcat-users. Inside of that there will be several commented out examples showing how to create a user. If you want to grant all roles that allow access to the admin manager app, you can add the lines of code below, changing the username and password.

<!-- Inside <CATALINA_HOME>/conf/tomcat-users.xml -->
<!-- Inside the <tomcat-users> element -->

<!-- Roles for Web Application Manager /manager/html/ -->
<role rolename="manager-gui" />
<role rolename="manager-script" />
<role rolename="manager-jmx" />
<role rolename="manager-status" />
<!-- Role for Virtual Host Manager /host-manager/html/ -->
<role rolename="admin-gui" />

<!-- Create user and assign roles -->
<user username="dano" password="secret" roles="manager-script,manager-gui,manager-jmx,manager-status,admin-gui" />

Note you will need to restart the server. If you installed it as a service, use your service manager to restart TomCat ("Services" in Windows; "sudo systemctl restart tomcat" in Ubuntu). If you installed it manually refer to the start and stop TomCat manually section above. Take time to explore the http://localhost:8080/manager/html and http://localhost:8080/host-manager/html links. If you are accessing it remotely and not via localhost, you will get errors. The next section explains how to whitelist your IP address.

Access admin web apps

To access the admin pages, visit the Web Application Manager at /manager/html (e.g. http://localhost:8080/manager/html) and view the Virtual Host Manager at /host-manager/html (e.g. http://localhost:8080/host-manager/html). The Web Application Manager, by default is only accessible on localhost. If you need to access the admin interface from a remote host, you need to whitelist your IP address on the server. You can do this by editing the META-INF/context.xml file inside the specific web app directory.

You will log in to these using the tomcat user and password created in the previous section in tomcat/conf/tomcat-users.xml.

To whitelist your IP, modify the file tomcat/webapps/manager/META-INF/context.xml and append your IP to the list of whitelisted IP addresses, separating your IP with the | separator (see the example below). Do the same for tomcat/webapps/host-manager/META-INF/context.xml

Find the line that looks like this in the <webapp>/META-INF/context.xml file:

&lt;Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />

Add your IP address to the list. We'll pretend it's 8.8.8.8. Change the allow property to include your IP address at the end, appended after a pipe | like this:

allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|8.8.8.8"

Manage web apps

Following the previous sections, you should already have access to the Web Application Manager, available at the /manager/html URL. This page will list the web apps that are available and running. You can start, stop, and undeploy apps from this page. You can also deploy web apps as packaged .war files or as exploded directories. If you are accessing the server remotely, the .war file is the choice you want.

Learn more about the Web Application Manager in the official documentation.

Conclusion

TomCat is a servlet container that has been around and proven its value. It's a solid choice for hosting JSP and servlet applications. After reading this you should feel comfortable setting up TomCat for basic usage to get started. This guide was only a quick overview of some common tasks. There are many more capabilities that TomCat has. Check out http://tomcat.apache.org/ for the latest and most accurate information.

References

Advertisement

Advertisement