In one of our recent projects, we needed to save the HTTP session in the database.
This blog refers the Apache documentation as found here: http://tomcat.apache.org/tomcat-6.0-doc/config/manager.html
These are the following steps that need to be followed:
Step 1: Create a database named tomcat (as shown in our example in Step 3 below) or any other name as specified in the ‘connectionURL’ attribute of the <Store> element.
Step 2: Create the following table in the newly created database:
create table sessions ( session_id varchar(100) not null primary key, valid_session char(1) not null, max_inactive int not null, last_access bigint not null, app_name varchar(255), session_data mediumblob, KEY kapp_name(app_name) );
Step 3: Copy the context.xml file available at the global level at this location: <TOMCAT_HOME>/conf to your application’s META-INF folder and replace the <Manager> element with the following:
<Manager className='org.apache.catalina.session.PersistentManager' saveOnRestart='false' minIdelSwap='0' maxIdleSwap='0' maxIdleBackup='1'> <Store className="org.apache.catalina.session.JDBCStore" driverName="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/tomcat?user=username&password=password" sessionTable="sessions" sessionIdCol="session_id" sessionDataCol="session_data" sessionValidCol="valid_session" sessionMaxInactiveCol="max_inactive" sessionLastAccessedCol="last_access" sessionAppCol='app_name' /> </Manager>
If these settings are placed in the ‘<TOMCAT_HOME>/conf/context.xml‘, it will have a global effect on all the applications running on the server. For an application specific setting, you can place a newly created “context.xml” file in the <APP_HOME>/META-INF sub-folder inside the webapps folder.
Please note that attributes used in the <Store> element make use of the table columns as created in the database in Step 2.
Step 4: Set the following system properties named – ‘org.apache.catalina.session.StandardSession.ACTIVITY_CHECK‘ to ‘true‘.
For further information on this, read the ‘Persistent Manager Implementation’ section at this link : http://tomcat.apache.org/tomcat-6.0-doc/config/manager.html
Step 5: Make sure you have placed the MySql jar in the <TOMCAT_HOME>/lib folder.
Now you can try to hit the application’s URL and check the database table to see the newly persisted session. Please note that it takes around 60 seconds to see the stored session in the database so you might have to wait a bit. You can have multiple instances of tomcat running your application pointing to the same database and can share this persisted session in case any of the tomcat instance crashes.
Abhishek & Imran
firstname.lastname@example.org | email@example.com
[Intelligrape Software Pvt. Ltd.]