1

I have a txt file have a sequence of integer such as : " 15 20 30 21 17 6 28 34 " I read the file and put the number to a arraylist I want get the value with position in arraylist by a servlet when request to server.

But now I want read txt file as soon as server start . I've put the read file function on the constructor function of servlet but it not run. Please help me.Thanks

edcon
  • 21
  • 3

1 Answers1

3

You can add a ServletContextListener to web.xml and implement your code in the method contextInitialized.

web.xml:

<listener>
    <listener-class>my.something.MyServletContextListener</listener-class>
</listener>

Implementation:

public class MyServletContextListener implements javax.servlet.ServletContextListener {
    public void contextInitialized(final ServletContextEvent event) {
        // code
    }
}

Or just load the servlet on startup:

<servlet>
    <servlet-name>MySerlvet</servlet-name>
    <servlet-class>my.something.MyServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
proko
  • 1,180
  • 1
  • 7
  • 14
  • 1
    or a servlet which loads on startup. Upvote. – Suresh Atta Oct 05 '15 at 04:52
  • True, depends on the needs and the implementation (servlet implementation can be changed). Updated the answer. – proko Oct 05 '15 at 04:55
  • If I load the serlvet on startup , where I put the reading file function ? Thanks – edcon Oct 05 '15 at 10:34
  • this is NOT when tomcat starts... – Enerccio Dec 10 '19 at 09:24
  • This is executed after the ServletContext was initialised. Nowadays there are alternatives with CDI/EJB. Have a look here: https://stackoverflow.com/questions/3468150/using-special-auto-start-servlet-to-initialize-on-startup-and-share-application – proko Feb 10 '20 at 05:54