CHAPTER 2: Building Web Applications Using Servlets and JSP 63
The ServletConfig object can be used to do the following:
Pass deploy-time information to the servlet (such as a database or enterprise
bean lookup name) that you do not want to hard-code into the servlet. This
deploy-time information is called the servlet init parameters. The servlet init
parameters will be discussed in the next section.
Access the ServletContext.
The ServletContext object can be used to do the following:
Access the web application parameters
Set attributes that all components of the application can access
Get server information, including the name and version of the container and the
version of the API that is supported
A servlet can have three types of parameters:
Request parameters
Initialization (init) parameters
Context-initialization (context-init) parameters
Initialization Parameters
The initialization parameters are defined in the web.xml file, as illustrated in Listing 2-5.
Listing 2-5. Defining Initialization Parameters
You cannot use init-parameters until the servlet is initialized. Your servlet inherits
getServletConfig(), so you can call that from any method in your servlet to get a reference to a
ServletConfig. Once you have a ServletConfig reference, you can call getInitParam().
When the container initializes a servlet, the following happens:
- The container makes a unique ServletConfig for the servlet.
- The container reads the init parameters from the deployment descriptor and
sets them in the ServletConfig object. - The container then passes the ServletConfig to the servlet’s init
(servletConfig) method.