Debugging the init() method in a Java servlet

java, servlets, tomcat

Solution

It seems to me like your deployment descriptor servlet declaration doesn't have an `load-on-startup` value bigger than 0. If you have omitted that element, the `Servlet` will only be initialized when the container deems that it should handle a request. Until then, the `init` method is not called.

By providing the `load-on-startup` value, like so

 <servlet>
    <servlet-name>servlet</servlet-name>
    <servlet-class>com.example.YourServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

You are telling the container to initialize the `Servlet` right away, therefore invoking your `init` method on startup, rather than when the first request for that servlet arrives.

Problem

From what I know about how a Tomcat server works, is that if you have a Java servlet in your web application, the `init()` method is called whenever the server starts up. In that case, how can I debug the `init()` method? Putting a break point clearly doesn't work, and for some reason `System.out.println` statements also do not yield any output on my server console. I have checked that the correct web app (`.war`) is deployed and it extracts correctly in the `webapps` folder of my Tomcat server.

Original source