Friday, November 11, 2011

Tomcat Servlet Context initialized twice or multiple times

Tomcat Servlet Context initialized twice or multiple times
I have seen this issue both in JBoss and Tomcat and in both cases this is about a miss configuration. It is worth to be said this issue affects the agility of the developer because extra time needs to be spent just waiting for tomcat to finish its initialization. This is also an issue that hits production systems many of which have very slow startup just because of miss configurations.

The first thing that you need to do is to include a log INFO level message when the servlet context is initialized like below:
public class ApplicationServletContextListener implements
        ServletContextListener {
    Logger log = LoggerFactory.getLogger(ApplicationServletContextListener.class.getName());
    public void contextInitialized(ServletContextEvent event) {
       ..."Servlet Context initialized");

Now whenever you restart your server you should get only one line:
2011-11-11 16:29:38,027 INFO [com.nestorurquiza.utils.web.ApplicationServletContextListener] -   Servlet Context initialized

If you get more than one look for errors in server.xml. Just to show an example of something that actually hit me Today this was the configuration in one of my servers:
<Host name=""">
  <Context path="" docBase="/opt/tomcat/webapps/nestorurquiza-app"/>

Just changing for the below fixed the issue:
<Host name="" appBase="webapps/nestorurquiza-app"/>

However it also screwed the root context you get with the previous configuration. If you still need the application to respond to the root context you will need to deployed as ROOT.war as explained in the official documentation.

No comments: