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.

There are two variants of the init method:

      init()

This is the convenient variant to override for initializing servlets. In this case, you need to retrieve the ServletConfig object inside the method body, and use it to get initialization parameters.

      init(ServletConfig)

In this case, the Web Container passes the ServletConfig object to the method. You need to call the super.init(ServletConfig) method at the beginning of the method body.

Procedure

Using the init() Method

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.

Example

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

<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>

The source code below retrieves the multiple initialization parameters:

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);

     }

}

Using the init(ServletConfig) 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 ServletContext object and initialization parameters.

 

 

End of Content Area