简体   繁体   中英

What is the proper way to create a file in your server after the application starts?

So I'm trying to do a simple web-app using the default stuff (Tomcat, no framework).

What I want is after I start server, I want my application to create a "Sample.txt" file in my server using a "SetUpDataService.class". Is there a way to do that?

Im thinking creating a "SetUpServlet" without mapping and just call the "SetUpDataService.class" in the init method, but it looks so dirty and feels wrong.

What is the best way for that using the default stuff? And is there a library exists for that purpose? Currently im not using any 3rd party library to strengthen my core understanding of JavaEE.

PS. I dont know if this question exists.I just cant find the right keyword so I posted this question.

EDIT: How about creating initial data on database? Is the approach OK?

Just for knowledge if you wanted to do that, you can achieve that using ServletContextListener as shown below. contextInitialized() method will be called by the container during startup (ie, when the servletcontext object is being created).

    @WebListener
    public class MyProjectListener implements ServletContextListener {

        @Override
        public void contextInitialized(ServletContextEvent sce) {
            //add your file creation code here
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            //add code cleanup the resources
        }
    } 

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