Category Archives: tomcat

How to change tomcat log directory ?

Log files are written by the Tomcat valve AccessLogValve. A valve, Tomcat only, is a Java class that preprocesses access requests. You can associate valves in server.xml to the containers engine, host and context.

Search TOMCAT_HOME/conf/server.xml for “AccessLogValve”. Specify the attribute directory as shown in this example:

<Valve className=”org.apache.catalina.valves.AccessLogValve”
       directory=”c:\tomcat\logs”  prefix=”localhost_access_log.” suffix=”.txt”

This will cause all the access logs of the hosting container to be written to c:\tomcat\logs.

Tomcat loadbalance using mod_jk part-2

How to maintain session in tomcat with load balance?
We alredy seen that how to implement load balance with tomcat.
In this process there is a problem that tomcat cant maintain session during load balance.
Session is a key value pair. Session will be created if there is no session id in request header.
Once session is created it will send with response and the session value will be set in client browser.
Http is a stateless protocal so server cant find the session directly. So it will read the session id from request and the session id will be checked with group of session id. If id matches the same session id will be maintained else new session id will be created.
So for ever request new session id will be created. This problem will be resolved if the preceding request are dispatched to same tomcat or all tomcat’s should have same session id. Here request will be dispatched to different tomcat instance in round robin method.
There is two way to resolve this session issue. Those are Session Affinity/Sticky Session and Session Replication.

Session Affinity/Sticky Session:
if you have many instances of tomcat (eg: tomcat1 & tomcat2) and you start session on tomcat1, the subsequent requests will be forwarded to tomcat1 as long as tomcat1 running an up (you never reach tomcat2). It means that if tomcat1 now is down, then your subsequent request will be forwarded to tomcat2, with a different session (a new session created at tomcat1 for you). This is not very good because if your application responding on tomcat1, then moved to tomcat2, session data will be lost. Usually Sticky session is achieved in simple load balancing of Apache server in front of tomcat servers.
Session Replication:
Session replication, means you will have the same session id regardless of your first or subsequent requests served by tomcat1 or tomcat2. It means that you session will be duplicated on both tomcat1 and tomcat2. Sometimes you served by tomcat1, sometimes you served tomcat2, although none of them is down. Usually this is achieved when tomcat cluster is created.

How to implement Session Affinity?
Session Affinity means redirecting all the reequests to the same tomcte.
Tomcat configuration file (conf/server.xml) contains a tag called has a property jvmRoute.
Session Affinity will be configured by assigning the tomcat instance name to this property.
So each and every session id will contain its tomcat instance name at end. So load balancer will easily find that to which tomcat instance the requests should be dispatched.
eg). {Session-id}.tomcat1
Sample Engine Tag:-


Note : – The above lines should be added in all tomcat’s context.xml file.
org.apache.catalina.session.PersistentManager is the class for Persistant Manager.
org.apache.catalina.session.FileStore is the class reperacents type of persistant manager.
directory – reperacentsfile path in the local machine.
Lets test the Manager :-
Create a jsp file to test which tomcat receives request.
# Create file Test/sestest.jsp
Note: create for each instance and change the tomcat instance name above

<%@page language="java" %>

Session serviced by tomcat1

<% session.setAttribute("abc","abc");%>

Session ID <%= session.getId() %>
Created on <%= session.getCreationTime() %>

  1. Open a browser to http:///examples/jsp/sesstest.jsp
  2. Click a number of times, you should stay with the same instance (sticky session working)
  3. Shutdown an instance
  4. Retest using the browser and hopefully it should pickup the other instance but have the same session ID
JDBC Store :-
Similarly in JDBC store session details will be stored in database. Here i am going to use mysql database. You can use any RDBMS database.
Make sure that table is already created in database to store session.
Samle Query to create Table :-
create table tomcat_sessions (
session_id varchar(100) not null primay key,
valid_session char(1) not null,
max_inactive int not null,
last_access bigint not null,
app_context varchar(255),
session_data meduimlob,
KEY kapp_context(app_context)
Sample Context.xml configuration :-

Lets test the Manager :-
Do the previous steps to test jdbc store.
3. Delta Manager :-
In Delta Manager once session is created for session for any tomcat instance, this session will be copied to all tomcat instances. So that all tomcats will have same session id. If current tomcat instant goes off , any off the tomcat will receive’s the furthor request. Since all tomcat have same session, data will not be lost and no more session will be created.
But its not a good approch for large size cluster. Because every time it copies the session to all the tomcat instances. So it will take more time.
To setup Deta Manager we has to follow these steps :-

1. Enable the Web Application as distributable
We need to make the our web application distribuable. its simple add tag in web.xml file. In according to servlet specification tag in web.xml mention that any container to consider this application can work in distributed environment

example :-
Add any of this tag in web.xml file.


2. Add Entries in conf/server.xml filefor all instances.

we can add this tag in either inside the tag or tag.


dropTime=”3000″ />

maxThreads=”6″ />

filter=”.*\.gif;.*\.js;.*\.jpg;.*\.htm;.*\.html;.*\.txt;” />

watchEnabled=”false” />

Note: the port in bold is the one you need to change for each instance

here most of the code are boiler plate code. just copy and paste. if we need we can customize. for example we can change the multicat address and port number.

hereManager tag define the delta manager. Delta manager meansreplicateto all instances.

Tomcat Clustering use the Apache Tribes communication framework. This group commnicationframeworkis responsible for dynamicmembership(usingmulticast) , send andreceivethe session delta information usinguni-cast(normal TCP connection).

This is Membership definition. here address is multicast address. we can pick any address from Class D address range ( to any port number.

Each and every tomcat send the heart beat signal to multicast address inperiodic(frequency) interval. all other tomcat whose joined the multicast address they canreceivethese signals and add the membership to the cluster. if heat beat signal is notrevivesomeparticularinterval(dropTime) from any one of the tomcat, then we need to consider that tomcat is failed.

All tomcat instances which is part of the clustering, should have same multicast address and port number.

here sender use the PooledParallelSender have pooled connections to use the send the session informationconcurrently. so its speedup the session replication process.

here we define which port Receiver can bind and used for receiving the session replicate information. here two properties are important. address and port. here address is ur system IP address and port is any unused port. hereaddress=”auto” its automatically pick the system IP address.

we have some interceptor
TcpFailureDetector-Its ensure that instance are dead. In some case multicast messages are delayed, all tomcat instances are think about that tomcat is dead. but this interceptor to make tcp unicast to failed tomcat and ensure that instances is actually failed or not.

another important listener is JvmRouteSessionIDBinderListener.

JvmRouteSessionIDBinderListener  take care to change the client session id to tomcat2 when failure is occurred  so load balancer redirect to tomcat2 without confusing.

3. Enable Multicast routing: –

In Linux Environment most of the system kernel is capable to process the multicast address. but we need to add route entry in kernel routing table.
sudo route add -net netmask dev eth0

here eth0 is myEthernetinterface. so changeaccordingto your interface
Inmulticastaddress is belong to Class D address Range( to so we inform to kernel if any oneaccessthese address then it goes through eth0 interface.
Note :-
make sure that the element is commented out.

4.Backup Manager :-
Backup Manager is replicate the copy of session data to exactly one other tomcat instances. This big difference between both managers. here which tomcat creates that is primary copy of the session. and another tomcat whose hold the replicate session is backup copy. If any one of the tomcat is down.
To setup a persistent session manager you must comment out the element in each instance, this disables the In-Memory replication mechanism, then add a context.xml file to each instance with the below.
The setup process of backup manager is same as Delta manager. except we need to mention the Manager as BacupManager (org.apache.catalina.ha.session.DeltaManager)  inside element.

Sample :-

dropTime=”3000″ />

maxThreads=”6″ />

filter=”.*\.gif;.*\.js;.*\.jpg;.*\.htm;.*\.html;.*\.txt;” />

watchEnabled=”false” />

Tomcat Load Balance using Apache and mod_jk.

What is load balance?
Load balance means dispatching the request between two or more tomcats.
Here all the tomcats which are wants to participante in the load balance will be grouped.
The Group of tomcat is called as tomcat clusters.
What is the need of load balance and tomcat cluster?
Mostly servers will run in single machine. There is a posibility anytime that machine can go down due to any os correption or harderware failure. So if it happens you cant access the server anymore.
So your site will be completely down. To resolve this we need tomcat cluster with load balance.
If any server goes down, the whole network will not go down. That is, if Load balancer receives any error message form a server it will redirect the request to the any of the remaining server. The servers in clusters will be selected using round robin method.
How to resolve the communication problem?
There is a way, By implementing load balancer you can resolve this issue. This load balancer will be added in from of all tomcat clusters. Here all the request and response will go through the load balancer.
So load balance will take care about dispatching the requests between tomcats which are in cluster.
There are Two effective load balancers are available.
  1. Apache http server
  2. Nginx
In this tutorial we are going to see Load balance using Apache Http Server.
What are the Software’s are required for Apache load balance?
  1. Apache Http server
  2. mod_jk
  3. tomcat cluster (many instances).
First install all the required softwares. In two different way you can install these, by using source code or apt-get. Using source code is always good because you can install only required things and at user specified place.
Here we are going to see how to build and install using source code.
How to install Apache Http Server?
First download the httpd server source code from then extract it and install.
You cant directly install using source code, you have to build to make Make file to install.
Steps to build:-
./configure –prefix=/usr/local/apache –enable-rewrite=shared–enable-proxy=shared
sudo make install

–prefix is the location where it is going to install in the machine.
–enable-rewrite and –enable-proxy options to enable these module in shared mode. These modules are not needed now. but we need in future for rewrite theURLbefore handover to next chain of servers and load-balancing support.
How to install mod_jk?
By using Apache http server alone we cant do load balance. Because by default Apache wont support AJP connector (ajp protocall).
So we need a linker to connect Apache web server and Ajp protocall. So here mod_jk going to be only a linker between appach and ajp protocall.
download the mod_jk connector module from it and follow the given steps to build.
cd tomcat-connectors-1.2.37-src/native
./configure –with-apxs=/usr/local/apache/bin/apxs
sudo make install
here–with-apxsoption to specify where apxs module is located. so weneedto giveApachehttpd server location.
nowmod_jk.sofiles is created on modules directory in apache installed location (/usr/local/apache/modules)
How to configure mod_jk connector?
You have to do two thinks to configure mod_jk.
  1. Creating file
  2. Configure mod_jk connector in apache httpd.conf file.
How to create file?
Get into apache/conf folder and create file.
Its a configuration file to make communicate between tomcat and ajp protocal using mod_jk connector.
sample :-




type is ajp13, port is ajp port and host is tomcat instance.
Here tomcat name and balancer name is user defined names. So you can give any name whatever you want.
balancer type is lb. Its a special type for load balance.

Status property is optional. It is used to get the load balance status and logs.
All requests are received by balancer and those are handled and dispached by balance_workers.
Because balance_workers have all tomcat instances names which are participating in load balance.
Actually to forward the requests to the balance_workers we need to configure httpd.conf file.
Do refer the following line if you need more details abt file.
How to configure httpd.conf file?
File path of httpd.conf is apache/conf/httpd.conf
Just add these following lines at the end of httpd.conf file.
JkWorkersFile conf/
JkLogFile logs/mod_jk.log
JkLogLevel emerg
JkLogStampFormat “[%a %b %d %H:%M:%S %Y] ”
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
JkRequestLogFormat “%w %V %T”

JkMount / balancer
JkMount /status stat

* JkWorkersFile will represent the location of the file.
* LoadModule is used to load module.
The last 2 lines are important.
JkMount /status stat means any request to match the /status then that request forward to stat worker. Its status type worker. so its shows status of load balancer.
JkMount /* balancer this line matches all the request, so all request is forward to balancer worker. In balancer worker is uses the round robin algorithm to distribute the request to other tomcat instances.
What about tomcat instance failover?
There is a default property called worker.maintain.
Every 60 seconds worker.maintain will send request to update the status of the all tomcat instances. If worker.maintain didnt not receive respone from any instance it will update the status as fail.
This process will be continued. If it receives any response from instance’s it will update the status to ok.
Thats it. Try it.. if u get any doubt please do let me know.

How to setup Virtual host in tomcat?

Virtual hosting means, setting up many websites under single tomcat.
That is hosting many websites into single tomcat.
What is the use of Virtual host method?
Virtual hosting is what most personal and small websites use for hosting. Instead of having a dedicated IP and machine where only your website lives, your site is hosted on a server with a bunch of other websites. In fact, most hosting today is on a virtual host.
For example if you want to run many website means, u should have to buy hosting space or server.
Instead of buying server/space you d\can deploy all your webapplications into single tomcat.
This process is called as Virtual hosting.
Where to configure?
Open tomcat/conf/server.xml
Give all the host name under section in server.xml
eg..” appBase=”anand_webapps” unpackWARS=”true” autoDeploy=”true” />
Copy tomcat/webapps folder and copy it parallel to webapps folder and rename it to appBase name in .
And deploy a war file into each appBase folders.
like this you can host any number of websites.
We can simulate the DNS setup in /etc/hosts file.
Open file /etc/hosts and give the following entries.
How it is working?
Each and every tomcat request will have details about the host in header. This host header will be checked with host’s which are given under section in server.xml.
If mached with any host, then tomcat will be pointed to corresponding appBase folder given in host and the request will be processed.
Thats it..
Type ur host name in browser and check it
Refer :-

How to Run Multiple Tomcat instancess in same machine?

Hi all in this post we are going to see, running multiple tomcat in a machine.
Before start you make sure that java is installed in your machine. Because to workwith tomcat you need java.
If u need any assistance to install java. Please refer post How to install java7 ?
What is apache and tomcat?
Apache-tomcat is a http server (web server).
Apache server is good to process static files like html, css and images.
Apache will process only static files, it wont process java or any backend files.
Tomcat server is good to process java (ie. Backend). Even Tomcat can process static files but when compare to apache, apache is best to load static files.
Difference between apache server and tomcat server?
Difference between webserver and application server?
How to install tomcat?
You can install tomcat in two different ways.
  1. Install throught terminal using sudo apt-get install tomcat ccommand.
eg. Sudo apt-get install tomcat7 manager admin user fonts.
    1. Download tomcate server from apache site and extract the tar.
Please refer post How to install tomcat? If you have any doubt.
In this post we are going to see second method.
How to run multiple tomcat?
Keep three copies of tomcat folder and name it like tomcat1, tomcat2, tomcat3.
Open tomcat1/conf/server.xml .
Give unique port address for connectors shutdown, http connector and Ajp connector of each
tomcat instances.
Start each tomcats.
Deploy any war file in each web apps folder.
How to deploy web application in to tomcat?
You can do it in two different ways.
  1. Copy war file difectly into tomcat/webapps folder.
  2. Through tomcat manager.
    • To delpoy throught tomcat you have to set tomcat user name and password.
    • For reference please refer post How to set tomcat username and password?.
Thats it … open tomcat url with correct http port.

How to enable ssl in tomcat?

First Generate SSl cirtificate.
If you don’t know about generating SSL certificate, please read post How to generate ssl certificate?
Then open tomcat/conf/server.xml
Go to ssl connector tag.
Add the following properties to the connector tag.
keystoreFile=”{{certificate location in ur machine}}”
keystorePass=”{{password of the certificate}}”
Test tomcat.
Eg https://localhost:8080/

How to Deploy .war file into Tomcat?

There is two way to deploy war (web archive file) in to tomcat.
Method 1: –
Copying war file directly into tomcat/webapps folder.
While start tomcat this .war files will be extracted.
Method 2: –
Deploying through tomcat manager.
For this you need to username and password for tomcat manager.
.war file will be extracted once it is deployed.
Its good practice to restart server once war file is deployed.

Struts Folder Structure in Tomcat (Apache)

Source From :-

Struts is one of the MVC Based Web frameworks in Java EE. It is used in creating simple web applications that are more flexible and easy to debug. Many of the blogs till have written about the folder structure of Struts and now i am going to discuss about the neat folder structure of struts in the Apache Tomcat version 7/6/5 or below.

The structure is mostly similar to that of the structure of the servlets/jsp. A little change can be noted here.


Note: Additional jar files in the lib directory may be needed example, struts-tiles-1.3.10.jar is necessary when you do use the tiles framework.

The classes directory: The classes directory should contain the relevant classes i.e. the Action class, Form Bean class (optional), MyRequestProcessor (Your own RequestProcessor class [Optional]), the Model class (optional). Optional means that these classes are not needed at all situations i.e. all applications. Usually a bean class and Model class is used when you interact with database. Helloworld example does not make use of these classes.

HTML Files: The HTML files and jsps are also seen in the servlets/jsp. So that is it.

web.xml: The web.xml file does the same thing as in the servlets. But with a little bit of change, later discussed on other posts.

struts-config.xml: This is the file that maps the action class for some user’s request. It is specified in the web.xml file. Note: As is specified in the web.xml, you can rename struts-config.xml to myconfig.myext and can also change where it is located. Whatever you do, you must specify the complete path along with the name and extension of this file in the web.xml.

webapps: Webapps folder is the webapps folder in the Tomcat. It comes by default when you install your tomcat. 

– See more at:

Servlets Folder Structure in Apache Tomcat

Webapps directory in Tomcat:
C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\

Note: Program Files is the place where software is installed in your computer, there you will find Apache Software Foundation, and there, Tomcat <version_installed>, in it webapps folder is present.
|_ project_name
|           |_ myhtml.html
|           |_ index.html
|   |_ classes
|          |_
|          |_ MyServlet.class
|_ web.xml
1. webapps contain project_name folder.
2. project_name folder may contain html files and WEB-INF directory is must.
3. WEB-INF folder contains web.xml and classes folder.
4. classes folder contains servlet classes.

Tomcat Web Application Directory Structure

What is webapps folder in tomcat?
webapps folder is the appBase for host name localhost.
This will be configured in conf/server.xml.


            unpackWARs=”true” autoDeploy=”true”>

you can change default webapps folder by editing appBase in host tag.


            unpackWARs=”true” autoDeploy=”true”>

What is exampleapp in the above image?
It is the name of the webapplication which is deployed in tomcat.

Here index.jsp is welcome file. This will be configured in web.xml file under WEB-INF folder.

–> this folder will contain all the images are used in this application.

This is optional folder.
Tomcat uses the Context configuration element to contain information about components required by a given application, such as databases, realms, or custom loaders.  Additionally, the Context element can be configured with a wide variety of attributes that control things such as loggingreload permissions, caching, and more.

This folder will not be visible to the end user.
This folder contains jar files (libs), java compiled codes(class files), properties files, xml’s and logs. 

–> this folder will have compiled codes of java files. 
Which will contain Java, Servlets, Filter , Struts, Hibernates (All java and j2ee codes ).. etc

This is the configuration file of web application.
Here Servlet, filter, web service mapping will be done with initial values.