简体   繁体   中英

REST: run main method from a jar located inside “/web-inf/lib” of a web project

I'm using Jersey 1.x and Tomcat 8.0. I have a .jar file which is my main application that I've uploaded to "/web-inf/lib" of a Dynamic Web Project.

I can't seem to figure out how to run a class which contains a main method inside this jar, which is crucial for my web service because It creates a connection to the Derby DB and all my web service methods are using these connections.

It has to start running when Tomcat server starts.

That is most definitely not the way to do it. If you want to have something run when Tomcat starts, take a look at ServletContextListener . Basically you implement this interface:

import javax.servlet.ServletContextListener;

public class MyContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // your init code goes here
    }
}

However, I question that even this is what you want to do. If you're using a local or embedded Derby instance then you're probably ok but now you'll have to distribute the connection information some how. Traditionally in an application like you have you'll use something like DBCP (included with Tomcat - take a look at the Tomcat DataSource docs ) and get the connection to the DB every time you need it. If you are just initializing the DB then ServletContextListener will allow that. But after that, don't use the ServletContextListener to also hand out database connections.

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