Welcome to my Tomcat tutorials website!

sabato 10 maggio 2014

Tomcat mod_proxy configuration

Configuring Tomcat with mod_proxy 

mod_proxy configuration is the simplest way to integrate Apache tomcat with Apache server. In order to do that,we need to add the module and redirect the URL to a virtual host.
Open the httpd.conf:
1. Place the following lines of code after the other LoadModule directives:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

2. Place the following lines of code with your other VirtualHost, or at the bottom of the file:

NameVirtualHost *
<VirtualHost *>
ServerName abc.com
ProxyRequests Off
<Proxy *>
Order deny,allow
Allow from all
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
<Location />
Order allow,deny
Allow from all
Save the configuration file and restart Apache Web server in order to test the integration using mod_proxy.
[root@localhost bin]# ./apachectl stop
[root@root@localhost bin]# ./apachectl start

How to configure Tomcat JVM parameters

How to increase JVM size in Tomcat

In order to change the JVM heap size for Tomcat, we need to pickup the catalina.sh/catalina.bat file and modify the value for the JAVA_OPTS parameter. For example, suppose we want to change the max heap size from 256 MB to 512 MB while setting the Perm Gen = 256 MB.
Here's how to modify the JAVA_OPTS:

JAVA_OPTS="-Xms128m -Xmx512m -XX:MaxPermSize=256m"

The changes in the JVM settings will take effect on the server restart. You can verify the change done in the JVM parameter by running the jmap command that is part of the JDK distribution. This tool requires passing the processId of Tomcat. Example:

C:\Users\tomcat>jmap -heap 3860
Attaching to process ID 3860, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 24.51-b03

using thread-local object allocation.
Parallel GC with 4 thread(s)

Heap Configuration:
   MinHeapFreeRatio = 40
   MaxHeapFreeRatio = 70
   MaxHeapSize      = 2122317824 (2024.0MB)
   NewSize          = 1310720 (1.25MB)
   MaxNewSize       = 17592186044415 MB
   OldSize          = 5439488 (5.1875MB)
   NewRatio         = 2
   SurvivorRatio    = 8
   PermSize         = 21757952 (20.75MB)
   MaxPermSize      = 85983232 (82.0MB)
   G1HeapRegionSize = 0 (0.0MB)

Heap Usage:
PS Young Generation
Eden Space:
   capacity = 68157440 (65.0MB)
   used     = 54483128 (51.95915985107422MB)
   free     = 13674312 (13.040840148925781MB)
   79.93716900165265% used
From Space:
   capacity = 5242880 (5.0MB)
   used     = 5232656 (4.9902496337890625MB)
   free     = 10224 (0.0097503662109375MB)
   99.80499267578125% used
To Space:
   capacity = 5242880 (5.0MB)
   used     = 0 (0.0MB)
   free     = 5242880 (5.0MB)
   0.0% used
PS Old Generation
   capacity = 88080384 (84.0MB)
   used     = 7874520 (7.509727478027344MB)
   free     = 80205864 (76.49027252197266MB)
   8.940151759556361% used
PS Perm Generation
   capacity = 22020096 (21.0MB)
   used     = 17099528 (16.30738067626953MB)
   free     = 4920568 (4.692619323730469MB)
   77.65419369652157% used

11415 interned Strings occupying 1616648 bytes.
The highlighted line of code in the previous code snippet is reflecting the value changed after the recycle in the JVM parameter.

Tomcat Context Path configuration

Tomcat context path configuration

Every time we deploy an application we need to setup a context path for the application. The context path will be used for accessing the application from a browser:
Even if it's actually possible to deploy an application on the Root Context Path ("/") this is usually reserved in special cases, for example if you need to provide a welcome page for your server or in other circumstances.

Enabling a context path

The context path in Tomcat can be enabled in two ways:

  • GUI using the Tomcat Web Application Manager
  • Command-line configuration in server.xml

In order to enable Context Path using the GUI interface, login into the Tomcat Application Manager:

You can create the context path using the Deploy tab.

Click on Browse and select the required WAR file. Then click on Deploy. It will take some seconds seconds to deploy the application (based on the application size) .
The following screenshot shows the application deployment status and administrative controls such as Stop, Reload, and Undeploy:

Once the application is deployed successfully, you can browse the application using its Context Path.

Command-line configuration in server.xml

Another way of adding the context path in Tomcat 7 is by editing server.xml. Let's quickly discuss the changes that need to be done on the Tomcat server:

<Context path="/myapplication" docBase="/www/" reloadable="true"
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="www-sample-com-log." suffix=".txt"

Now, it's time to discuss the parameters defined in the context path:

  • path="/myapplication": It defines the path URL for the server request, for example, http://localhost:8080/myapplication
  • docBase="/www/": It defines the document root for the context path. In simple language, this parameter defines the place from where the deployment .war file gets picked up.
  • reloadable="true": If this parameter is true, then every change done on the WAR file will be in effect automatically without a Tomcat recycle.
  • swallowOutput="true": If this parameter is set to true, then the output for System.out and System.err will be redirected to the application log.

Tomcat Manager Configuration

This tutorial shows how to configure the tomcat manager application that can be used to administrate Tomcat. We will also show how to enable the default user and password and how to grant the roles required to run the manager application.
The Tomcat Manager is a very powerful tool for Tomcat administration. It allows you to use the following features:

  • Remote application deployment 
  • Cleanup of Idle session
  • Application undeployment and redeployment
  • Analysis of memory leaks
  • JVM status
  • Server status

The Tomcat Manager by default is disabled in Tomcat 7. In order to enable it, pickup the tomcat-users.xml in the conf folder of Tomcat 7. This file contains two users: tomcat and role1. These roles however are not enabled to use the manager gui, as you need an user with the "manager-gui" roles. So change the file so that it look like this:


<role rolename="manager-gui"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>

Logging into the Manager with the default username and password

So now with the above changes, you will be able to login into Tomcat Manager application with Tomcat manager-gui user name and password that is tomcat/s3cret.

Through this console, we can deploy new applications or modify the current application's state to stop, undeploy, start, reload, clear sessions, and so on as displayed by the following picture:

Checking Tomcat Status

One interesting feature of Tomcat Manager is the ability to inspect the the current status of the server by clicking on the Server Status, as shown in the following picture:

The server status UI will show the following details:

  • JVM status (Max memory, Total memory, Free memory)
  • Connection of AJP port 8009  (Connection state, Data sent, Data received, Client, Virtual host)
  • Connection on HTTP port 8080 (Connection state, Data sent, Data received, Client, Virtual host)
  • Server information (Tomcat version, OS version, JVM version, System architecture)

domenica 4 maggio 2014

Tomcat Websocket example

A WebSocket is a full-duplex communication mechanism that allows both textual and binary messages to be sent between clients and servers, without the HTTP request/response life cycle. WebSockets allow either the client or the server to send a message at any time, providing an asynchronous solution for working with data while the user is performing a task.
Websockets API are included in Tomcat 7 Web server distribution so you don't have to download any extra library:

In this tutorial we will show how to create a WebSocket example using Apache Tomcat and Eclipse.
Start by creating on Eclipse a new Dynamic project named websocket-example:
We will now create a server side class named WebSocketDemo that is going to echo messages from a Javascript client:
package com.sample;

import java.io.IOException;
import java.nio.ByteBuffer;

import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

public class WebSocketDemo {

    public void echoTextMessage(Session session, String msg, boolean last) {
        try {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(msg, last);
        } catch (IOException e) {
            try {
            } catch (IOException e1) {
                // Ignore

The @ServerEndpoint annotation accepts a String-based path attribute, which is used to indicate the URI at which the server is available to accept client messages. Therefore, when the server is started, the value of the path attribute would be appended to the end of the context path and application name in which the WebSocket resides.
By initiating a call to that URL, one method, annotated with @OnMessage, will be invoked to process the message that is sent.
Here is the index.jsp file which contains a Javascript code and a form where you can enter a message:
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
        <meta charset="utf-8">
        <title>Your First WebSocket!</title>
        <script language="javascript" type="text/javascript">
            var wsUri = "ws://localhost:8080/websocket-example/echo";
            function init() {
                output = document.getElementById("output");
            function send_message() {
                websocket = new WebSocket(wsUri);
                websocket.onopen = function(evt) {
                websocket.onmessage = function(evt) {
                websocket.onerror = function(evt) {
            function onOpen(evt) {
                writeToScreen("Connected to Endpoint!");
            function onMessage(evt) {
                writeToScreen("Message Received: " + evt.data);
            function onError(evt) {
                writeToScreen('ERROR: ' + evt.data);
            function doSend(message) {
                writeToScreen("Message Sent: " + message);
            function writeToScreen(message) {
                var pre = document.createElement("p");
                pre.style.wordWrap = "break-word";
                pre.innerHTML = message;
            window.addEventListener("load", init, false);
        <h1 style="text-align: center;">Hello World WebSocket Client</h2>
        <div style="text-align: center;">
            <form action="">
                <input onclick="send_message()" value="Send" type="button">
                <input id="textID" name="message" value="Hello WebSocket!" type="text"><br>
        <div id="output"></div>

In this example, the message contained in the "message" input field will be sent as text message to the Websocket available at:
var wsUri = "ws://localhost:8080/websocket-example/echo";

Now startup Tomcat and deploy the application. Once that you have entered the message in the text field you should expect to read the echo message on the Web page:

mercoledì 30 aprile 2014

Tomcat session timeout

Tomcat session timeout is defined into the CATALINA_HOME/conf/web.xml file by the following directive:
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

You can however override the default session timeout by setting in your application's WEB-INF/web.xml file the session timeout as well.

The number in session-timeout tag is in minutes. To make it unlimited or no time out, simply set the number to -1 and restart your Tomcat Service.
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">


Tomcat configuration files

A Tomcat distribution contains the following configuration files which are necessary for proper administration of the Web server. Let's see in detail each file:

  • catalina.policy : This file contains the security policy permissions for Tomcat 7. It enforces the security policy permissions by JVM on the web application.
  • catalina.properties : This file describes the shared definition of the server, shared loader, and JARs, which need to be scanned at the time of the server startup.
  • server.xml : This is the main configuration file for Tomcat and it mainly contains the Connector port configuration. It holds critical information, such as the IP address, port, virtual host, context path, and so on.
  • tomcat-users.xml : This file is used for authentication, authorization, and role-based definitions. It is used to implement a database of users/passwords/roles for authentication and container-managed security. To add/remove users or assign/unassign roles to existing users, edit this file.
  • logging.properties : As the name suggests, it defines the logging properties of the Tomcat instances (such as startup logs).
  • web.xml : This file contains the default values for all web applications loaded into this instance of Tomcat, at the time of startup of the Tomcat instance. If a web application has its own deployment descriptor, its content will always override the configuration settings specified in this default descriptor.
  • context.xml : The contents of this file will load with every application. Configuration of parameters such as session persistence, Comet connection tracking, and so on, are done here.

Yum install tomcat on Linux

This tutorial shows how to perform a Tomcat 7 installation using the yum installation utility.
The pre-requisite for installing Tomcat is that you have a JDK on your machine, if you haven't got one, you can install it by executing as root user:
[root@localhost ~]#  yum install java
Next you can start installing Tomcat. There are at least two ways for installing it:

Installation option 1:

Move to http://tomcat.apache.org/ and download the latest stable release of Tomcat. Once done, unzip it to a folder where you have writing permissions:
[tomcat@localhost ~] $ unzip apache-tomcat-7.0.53.zip

Once installed, you can start Tomcat by executing from the TOMCAT_HOME/bin folder:
[tomcat@localhost ~] $ startup.sh

Installation option 2:

You can use the yum utility for installing Tomcat. At the time of writing, just Tomcat 6 is available on the yum repository. You can install it by running:
[root@localhost ~]# yum install tomcat6 tomcat6-webapps tomcat6-admin-webapps

The tomcat6-webapps is not mandatory as it contains some sample applications. The tomcat6-admin-webapps should be installed as it contains the administration application which is deployed as a web application. 
Once installed, you can include it as a service which starts at boot and start it:

[root@localhost ~]#  chkconfig tomcat6 on
[root@localhost ~]#  service tomcat6 start

Checking that Tomcat is running

The simplest way to check that Tomcat is running is by surfing to the address http://localhost:8080 which should show the welcome page:
If you are going to check it by shell, you can use the following methods to check that Tomcat is running:
[tomcat@localhost ~] service tomcat6 status
tomcat6 (pid 4470) is running...                           [  OK  ]

[tomcat@localhost ~] netstat -nlp | grep 8080
tcp        0      0 :::8080                     :::*                        LISTEN      4470/java           

[tomcat@localhost ~] ps -ef | grep tomcat
tomcat   1937     1  1 11:04 ?        00:00:08 /usr/lib/jvm/jre/bin/java
                                                       . . . . . . .

Where has yum installed Tomcat ?

If you have used yum to install Tomcat, the following defaults have been user for Tomcat installation:
Tomcat Service Config: /etc/tomcat6 (main config directory)
Release Notes        : /usr/share/doc/tomcat*
Bin Directory        : /usr/share/tomcat6
Webapps              : /var/lib/tomcat6/webapps
Logs                 : /var/log/tomcat6 

venerdì 25 aprile 2014

Tomcat Access logs

Access logs are customized logs, which record all requests processed by the server giving information about:

  • The user that has accessed the application
  • What components of the application are accessed
  • Remote IP and so on

These logs play a vital role in traffic analysis of many applications to analyze the bandwidth requirement and they also help in troubleshooting the application under a heavy load. These logs are configured in  server.xml in  TOMCAT_HOME/conf .
You can configure access logs according to the environment and your auditing requirements. Let's see the pattern format of the access logs and understand how we can customize the logging format:

And now some explanation about the parameters contained in the AccessLogValve:

  • Class Name: This parameter defines the class name used for the generation of logs. By default, Apache Tomcat 7 uses the  org.apache.catalina.valves.AccessLogValve class for the access logs.
  • Directory: This parameter defines the directory location for the log file. All the log files are generated in the log directory— TOMCAT_HOME/logs —but we can customize the log location based on our environment setup and then update the directory path in the definition of the access logs.
  • Prefix: This parameter defines the prefix of the access log filename, that is, by default, the access log files are generated by the name  localhost_access_log.yy-mm-dd.txt .
  • Suffix: This parameter defines the file extension of the log file. Currently it is in  .txt format.
  • Pattern: This parameter defines the format of the log file. The pattern is a combination of values defined by the administrator, for example,  %h = remote host address. 

How to change Tomcat port

By default, Tomcat runs on port 8080 using the HTTP protocol. As this port is well known by developers, it is easier for hackers to hit the port and trap the server. So it's always recommended to change the connector port and also the AJP port, which runs on 8009, to secure Tomcat.
Connectors are configured in server.xml in the conf directory of your Tomcat installation.

Before changing Tomcat port, you should verify that the port is not being used by other services. You can check the following operating system configuration files in order to avoid port conflict between the two services.

Linux: /etc/services
Windows: C:\Windows\System32\drivers\etc\services

domenica 13 aprile 2014

Tomcat users configuration

Configuring Tomcat users is required in order to be able to use Tomcat Manager application. The main configuration file for tomcat users is tomcat-users.xml that resides in the conf folder of Tomcat 7. In this file, user roles and their authentication are configured.
Here is for example how to configure it to add one user named tomcat that has all roles required to manage the manager GUI application and the Manager script shell:


tomcat connectiontimeout configuration

Apache tomcat contains a connectionTimeout parameter which defines the amount of time Tomcat will wait for three things:

  • The total amount of time it takes to receive an HTTP GET request.
  • The total amount of time between receipt of TCP packets on a POST or PUT request.
  • The total amount of time between ACKs on transmissions of TCP packets in responses.

Changing the connectionTimeout

In some cases it might be necessary to increase it especially if the response takes too much to be completed on the server, leaving the connection without a response. To increase the connection timeout on tomcat server follow the following steps :

1. Open the file server.xml residing in TOMCAT_HOME/conf/.
2. Set the variable connectionTimeout in it to Value in Milliseconds.(i.e 1000 milliseconds = 1 second)

For example :

If connectionTimeout is not defined, the default value is 60000 (i.e. 60 seconds); however the standard server.xml that ships with Tomcat sets this to 20000 (i.e. 20 seconds).
You can use a value of -1 to indicate no (i.e. infinite) timeout.

Do not set this value to extreme values to avoid hanging your server threads for too much. On the other hand setting it to a value too low, might cause rejecting some of your requests,

Tomcat Maven plugin tutorial

This tutorial will show you how you can create a Web application with Maven and deploy it using Maven plugin for Tomcat in a matter of minutes. The prerequisite is that you have installed in your machine:
  • Apache Maven 2.X or 3.X 
  • Apache Tomcat 7.X  
  • JDK 1.6 or higher 
We will show how to create the project from Eclipse IDE. From Eclipse File menu choose to create a New | Maven Project:

In the next screen make sure that the option Create a Simple project (Skip archetype selection) is unchecked and select a Workspace for your project:

Click Next. In the following screen choose an archetype for your project. There are plenty of available Maven archetype that are suitable for a Web application to be executed on Tomcat. We would suggest to use the maven-archetype-webapp that will create a startup skeleton for your Web projects:

Finally in the last screen choose a GroupId for your project. Choose an ArtifactId that will match to the Eclipse project name. Select a Version and a Package for your project:

Click finish. Now a basic project will be included in your Eclipse Package explorer:

Configuring Tomcat Maven plugin

In order to be able to deploy/undeploy your project using Maven, we will add Tomcat Maven plugin to our pom.xml:


As you can see, Maven tomcat plugin is based on Maven tomcat7-maven-plugin. If you are using tomcat6 there is a corresponding tomcat6-maven-plugin. Within the plugin configuration we have included some configuration details to reach Tomcat Manager application. The most important part is the Manager URL which needs to be set to: http://localhost:8080/manager/text
Next, mind to include the username and password as contained in the tomcat-users.xml file:


That's all. In order to build and deploy your application on tomcat 7 using Maven shell, just issue:
mvn tomcat7:deploy 
As you can see from Tomcat 7 console, the application is now deployed:

sabato 29 marzo 2014

Tomcat Thread Pool configuration

In order to accept incoming requests, Tomcat uses a Thread pool. You can configure two types of Thread Pools: Shared Pool and Dedicated Pool.
A Shared pool as the name inplies, can be shared among various components in Tomcat. So, for example if you have three connectors in your configuration, then you can use a single shared pool to serve requests for all of them. Here is how to configure a shared thread pool:

Open Tomcat's server.xml file and include the Executor definition:





Once you have added the shared thread pool, you need to reference it in your Connector configuration as follows:





A Dedicated thread pool is a thread pool which is dedicated to only one connector definition. You can use it in a scenario when you are expecting a peak of connections and you want to have full control over the amounts of threads to be used by your connector.
The dedicated thread pool configuration can be embedded directly into the Connector section of your server.xml. See the following example:







sslProtocol="TLS" />

When to use a shared thread pool versus a Dedicated thread pool
Generally speaking a Shared Thread pool is best fit when the number of users expected is not hight and we don't care much about performance. This is the typical scenario for a Development Environment. On the other hand, for production environment when Performance is critical you should consider using a Dedicated Thread Pool.

Tomcat Datasource configuration using MySQL

Configuring a MySQL Datasource on Tomcat 

Pre-requisite. Download MySQL JDBC Driver from: https://dev.mysql.com/downloads/connector/j/

In order to configure a Datasource on Tomcat for MySQL Database you need to follow these three simple steps:

1) Define the Datasource in server.xml
Include a Datasource configuration in your Tomcat's server.xml file within the Context section, containing information about the JDBC URL, username and password and the maximum number of active connections allowed in the pool:

<Resource name="jdbc/MySQLDS" auth="Container" type="javax.sql.DataSource"
         validationQuery="Select 1" />

2) Install JDBC Driver 
Next, before starting up Tomcat place MySQL JDBC driver (e.g. mysql-connector-java-5.1.29-bin.jar) into CATALINA_HOME/lib/

3) Add a reference to the DataSource in web.xml 
Finally, in your web.xml reference your datasource by including the JNDI name assigned in your server.xml:

 <description>Oracle Datasource for tomcat </description>

Now you can look up your Datasource in your application as follows:
InitialContext cxt = new InitialContext();

DataSource ds = (DataSource) cxt.lookup( "java:/comp/env/jdbc/MySQLDS" );

if ( ds == null ) {
   throw new Exception("Data source not found!");

Tomcat Datasource configuration using Oracle

Pre-requisite. Download Oracle JDBC Driver from: Oracle JDBC Drivers are available at Oracle Site: http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html

In order to configure a Datasource on Tomcat for Oracle Database you need to follow these three simple steps:

1) Define the Datasource in server.xml
Include a Datasource configuration in your Tomcat's server.xml file within the Context section, containing information about the JDBC URL, username and password and the maximum number of active connections allowed in the pool:

<Resource name="jdbc/OracleDS" auth="Container" type="javax.sql.DataSource"
         validationQuery="Select 1" />
2) Install the JDBC Driver 
Next, before starting up Tomcat place Oracle JDBC driver into CATALINA_HOME/lib/ . For Oracle, either class 12.jar or ojdbc5.jar

3) Finally, in your web.xml reference your datasource by including the JNDI name assigned in your server.xml:

 <description>Oracle Datasource for tomcat </description>

Now you can look up your Datasource in your application as follows:
InitialContext cxt = new InitialContext();

DataSource ds = (DataSource) cxt.lookup( "java:/comp/env/jdbc/OracleDS" );

if ( ds == null ) {
   throw new Exception("Data source not found!");