Reading initialization Parameter
You can provide initialization parameters to a servict. These call be used-to open files create database connections, or perform other actions. Tl.is information can be accessed in two ways:
The init( ) method declared by the Servlet interface receives. a Servletconfig object as its argument. This object provides methods that enable you to read the initialization parameters. The getScrollInfo( ) method declared by the Servlet interface returns a Servletconfig object.
manner in which initialization parameters arc provided to a servlet is server-dependent. The servletrunner utility defines the initialization parameters for servlets in a file named servlet.properties. The default Ideation for this file is the Examples directory.
Now, let’s develop a servlet that reads some initialization parameters. The example contains two files: scrvlet.propcrtics and InitScrvlct.java. TIle file servlet.prupertics is shown in the following listing. It defines two properties for a servlct: scrvlct.nsure.code, which enables you to associate a name with thc class that contains the codefor the servlet, and scrvlct.usme.inltargs, which enables you to define a sequence of comma-delimited parameter names and values. For both properties, name is a string by which this servlet is to be known. The syntax of each parameter name and value is the following:
name =: paulus
where pnanie is the parameter name is Ih~parameter value.
In the following version of servlct.properties, you can see that thc name of the servlet is initservlet. Its code is located in the class InilServlct. Two initialization ‘parameters, named country and city, have the values Canada and Toronto, respectively. The source code for InttScrvlet.java is shown in the following listing. Here, the gctScrvlctConfig( ) method is called to obtain a ScrvletConfig object. The ‘ gctlnitf’arametert ) method is used to obtain the values for the two initialization parameters. These are then written to the HTTP response,
You can tcst this example by requesting BOSO/servlets initservlet in your browser. Output should appear as follows:
One other point: TIle URL must contain the name that is assigned to this servlet in the servlet.properties file, not the name of the servlet class. Otherwise, the in ialization parameters.cannot be read.