10

I have a class that takes a bit of time to start up (makes some JNI calls and what not), so it is not feasable to initialize this class everytime a page loads. Is it possible to initialize this class on application startup, then access its methods as pages are being served up?

For Example:

I have MyClass. When the application (tomcat) starts up I would like it to initialze my calss as follows:

MyClass myClassInstance = new MyClass("arg1", "arg2");

Then when a page is called, say /testpage, I would like to make calls to myClassInstance:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import MyClass;

public class TestPage extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        String myResult = myClassInstance.getResult("whatever");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Test</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>" +myResult +"</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

Is this possible?

Petey B
  • 11,439
  • 25
  • 81
  • 101
  • Related: http://stackoverflow.com/questions/3468150/using-init-servlet, http://stackoverflow.com/questions/3153739/config-files-for-a-webapplication-load-once-and-store-where, http://stackoverflow.com/questions/5951294/is-there-a-way-to-do-something-on-a-j2ee-server-start-im-using-tomcat, etc – BalusC Jun 01 '11 at 20:19

3 Answers3

21

You have two choices:

  1. Initialize your class in servlet's init() method. You may add <load-on-startup> attribute to make sure your servlet is created at application startup and not on first access.

  2. Add ServletContextListener and use contextInitialized() callback method. Use ServletContext#setAttribute to store created object for future use.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
8

If you want it to happen once for the whole app, and happen before any servlet is run, implement ServletContextListener and put your startup code in contextInitialized(). Then set up your web.xml to specify your class as a listener.

Otherwise, you can do what the other answer says and put it in the init() method of the servlet.

QuantumMechanic
  • 13,795
  • 4
  • 45
  • 66
3

You can do the initialize of the class inside the servlet's init method.
init() method is invoked when the servlet instance is loaded so it is a good place for expensive operations.

Cratylus
  • 52,998
  • 69
  • 209
  • 339