0

I have a JSP/Servlet web application with some JSP pages and servlets. I have read the following questions:

  1. Servlet constructor and init() method
  2. Using special auto start servlet to initialize on startup and share application data

They were very helpful, but I have a new question: do I need to initialize every servlet I use? Or do I have to init() only the first serlvet that is called in my web application?

Community
  • 1
  • 1
yaylitzis
  • 5,354
  • 17
  • 62
  • 107

2 Answers2

0

Because the Servlet container controls the initialization of your Servlet, you don't have a choice but to use the init() method to initialize any instance fields that your Servlet might need. For example if your Servlet depended on a Service class to interact with some resource, you could do the following

public class MyServlet extends HttpServlet {

    private MyService myService;

    public void init() {
        myService = new MyService();
        myService.setSomeProperty("propertyValue");
    }
    ...
}

This way you can initialize any fields. If you need it, you can use the init(ServletConfig) method instead or call getServletConfig() to access the ServletContext which may contain attributes that were added either from other Servlet init() or from ServletContextListeners. Note that you can set in which order your Servlets will be initialized.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

It look like that you completely misunderstood the purpose of servlet's init(). You seem to think somehow that you must override it. This is completely untrue. It just gives you the opportunity to declare a servlet method which should be invoked only once on servlet's initialization during application's startup. Usually, to initialize some local variables based on some services or configuration files or servlet's own <init-param>. Please note, local variables, thus the ones specific to the servlet instance itself which are declared private and are never shared/accessed elsewhere outside the servlet.

Particularly the following statement

Or i have to init() only the first serlvet that is called in my web application?

suggests that you're actually looking for an application-wide hook which is invoked during application's startup. In that case, you should be using a ServletContextListener instead of servlet's init() as answered in the Using special auto start servlet to initialize on startup and share application data question. Here's a Servlet 3.0 compatible kickoff example without the need to add a <listener> entry to web.xml:

@WebListener
public class Config implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        // Do stuff during webapp's startup.
    }

    public void contextDestroyed(ServletContextEvent event) {
        // Do stuff during webapp's shutdown.
    }

}
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555