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
</Proxy>
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
<Location />
Order allow,deny
Allow from all
</Location>
</VirtualHost>
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:
http://SERVER:PORT/Context-Path/Resource
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"
swallowOutput="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="www-sample-com-log." suffix=".txt"
timestamp="true"/>
</Context>

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:

<tomcat-users>
 

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

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;

@ServerEndpoint("/echo")
public class WebSocketDemo {

    @OnMessage
    public void echoTextMessage(Session session, String msg, boolean last) {
        try {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(msg, last);
            }
        } catch (IOException e) {
            try {
                session.close();
            } 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:
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    </head>
    <body>
        <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) {
                    onOpen(evt)
                };
                websocket.onmessage = function(evt) {
                    onMessage(evt)
                };
                websocket.onerror = function(evt) {
                    onError(evt)
                };
            }
            function onOpen(evt) {
                writeToScreen("Connected to Endpoint!");
                doSend(textID.value);
            }
            function onMessage(evt) {
                writeToScreen("Message Received: " + evt.data);
            }
            function onError(evt) {
                writeToScreen('ERROR: ' + evt.data);
            }
            function doSend(message) {
                writeToScreen("Message Sent: " + message);
                websocket.send(message);
                //websocket.close();
            }
            function writeToScreen(message) {
                var pre = document.createElement("p");
                pre.style.wordWrap = "break-word";
                pre.innerHTML = message;
                 
                output.appendChild(pre);
            }
            window.addEventListener("load", init, false);
        </script>
        <h1 style="text-align: center;">Hello World WebSocket Client</h2>
        <br>
        <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>
            </form>
        </div>
        <div id="output"></div>
</body>
</html>

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: