Often servlets need external resources such as property files, folders, database drivers etc, for request processing. Hard coding these resources into the Servlets creates maintenance problem because if their name, value or location is changed, the Servlets need to be modified.
To facilitate the use of external resources in servlets in such a way that they can be changed without modifying the servlets, concept of initialization parameters is provided by the Servlet API. An Initialization parameter represents textual information as key value pair. It can be the name of a file, path of a folder, a driver class or any other information required by the servlets. It is defined by the programmer in web.xml file and is made available to a servlet or servlets of the application by the server.
Initialization parameters can be of two types:
Servlet specific initialization parameters are used to provide information to a specific servlet of the application. They are defined using <init-param> sub element of <servlet> element in web.xml.
Application specific initialization parameters are used to provide information to all the servlets of an application. They are defined using <context-param> sub element of <web-app> element in web.xml.
Syntax of defining initialization parameters:
<web-app> <!-- application specific initializaiton parameters, multiple context param can be defined for the servlets. --> <context-param> <param-name>Name</param-name> <param-value>Value</param-value> <context-param> ... <servlet> <servlet-name>ObjName</servlet-name> <servlet-class>ClassName</servlet-class> <!-- Servlet specific initializaiton parameters, multiple init param can be defined for a servlet. --> <init-param> <param-name>Name</param-name> <param-value>Value</param-value> </init-param> ... </servlet> ... </web-app>
How the server provides initialization parameters to the servlets:
To provide initialization parameters to the servlets of an application, a web server uses objects of type ServletContext and ServletConfig. Both ServletContext & ServletConfig are interfaces of the Servlet API. Their implementation is provided by server vendors i.e. each java web server has classes which implement these interfaces.
For each web application, an object of type ServletContext is created by the server at the time of deployment. This object is also called application object because it has application scope i.e. it remains in the memory as long as the application remain deployed. It has following use:
For each servlet, an object of type ServletConfig is created by the server. It has following use:
Following diagram describes the role of ServletConfig & ServletContext:
Description of the diagram:
In the next post, we will learn how a servlet can obtain initialization parameters from the SevletConfig & Servletcontext objects.