简体   繁体   中英

Deploying Java Application As Servlet

I have a java application that up until now was run as a stand alone java application (ie 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.

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. Eg

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 .

I'm assuming that your app is continuously running and you have an app/web server already (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM