views:

108

answers:

2

I have a java application that up until now was run as a stand alone java application (i.e. executable jar). I now need to deploy it in Tomcat as a servlet. It doesn't need to actually process any HTTP requests though, but it needs to be started using tomcat.

What are the steps required to convert the project so that it can be deployed in Tomcat? I'm using maven as a build tool and Java 1.5.

+2  A: 

I'm assuming that your app is continuously running and you have an app/web server already (e.g. Tomcat/Jetty), such that it's making your life easy to deploy into it. Given that, you need to:

  1. extend an AbstractHttpServlet class and in particular the init() method. This would start your app.
  2. build a web.xml that references this and sets the load-on-startup attribute to 1 (or at least non-zero)
  3. build a .war from this and deploy it

Step 2 ensures that the init() method is called upon deployment/server reboot, and so you don't have to respond to HTTP requests (a normal startup trigger for a servlet).

It may be simpler and more appropriate to use something like javaservicewrapper, and wrap it up to be a Windows service or similar.

Brian Agnew
+1: basically, AbstractHttpServlet.init() is just another entry point, ala public static main(String[] args) for a regular cmd line started app.
Trevor Harrison
+5  A: 

I understand that you want to run this app on server's startup. The best way would be implementing ServletContextListener and run the app in the contextInitialized() method. E.g.

public class Config implements ServletContextListener {

    private YourApp yourApp;

    public void contextInitialized(ServletContextEvent event) {
        yourApp = new YourApp();
        yourApp.start();
    }

    public void contextDestroyed(ServletContextEvent event) {
        yourApp.shutdown();
    }

}

Register this in web.xml as follows:

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>

That's it. No need to wrap it in flavor of a HttpServlet as you aren't going to fire HTTP requests on it.

You however need to ensure that it runs in its own thread, otherwise it would block the startup. If it doesn't, then wrap it in a Runnable and execute it using ExecutorService.

BalusC