Show TOC Start of Content Area

Procedure documentation Initializing Servlets  Locate the document in its SAP Library structure

Use

The init() method of the servlet is invoked immediately after instantiating the servlet object. It is called by the Web Container only once per servlet declaration for the lifetime of the servlet. You can use this method to perform specific initializations or time-consuming actions that need to be done once for the servlet’s lifetime. Some examples are database connections, lookup of Enterprise JavaBeans, initializing local data, files and other resources. You must be aware that these resources are not released until the servlet is removed from the service.

You can also read the name-value pairs that you have provided as initialization parameters in the deployment descriptor of the Web application. You can obtain a reference to the servlet context of the Web application and the context parameters it provides.

Note

The application classloader is always set in the thread that invokes servlet methods. You can obtain it in the init() method of the servlet if your servlet needs to load additional classes of the application.

Retrieving Initialization Parameters

You can use the getInitParameter(String name) method. When passed the name of the parameter, this method returns the parameter's value as a String.

The example below retrieves multiple initialization parameters:

Syntax

public void init() throws ServletException {

  // Get all available initialization parameters

  Enumeration enum = getServletConfig().getInitParameterNames();

  while (enum.hasMoreElements()) {

      // Get the name of the init parameter

      String name = (String)enum.nextElement();

      // Get the value of the init parameter

      value = getServletConfig().getInitParameter(name);

     }

}

You have declared the following parameters in the web.xml of the application that contains the servlet:

Example

<servlet>

  ...

  <init-param>

    <param-name>parameter1</param-name>

    <param-value>value1</param-value>

  </init-param>

  <init-param>

    <param-name>parameter2</param-name>

    <param-value>value2</param-value>

  </init-param>

</servlet>

Overriding the init() Method

Use the super.init(ServletConfig) method to pass the ServletConfig object to your servlet. It is necessary because it provides servlets with access to the ServletContextobject and initialization parameters.

 

 

End of Content Area