Each registered servlet name can have specific initialization
Each registered servlet name can have specific initialization (init) parameters associated with it. Init parameters are available to the servlet at any time; they are often used in init ()to set initial or default values for a servlet or to customize the servlet’s behavior in some way. Init parameters are more fully explained in Chapter 3, The Servlet Life Cycle. Getting an Init Parameter A servlet uses the getInitParameter()method to get access to its init parameters: public String ServletConfig.getInitParameter(String name) This method returns the value of the named init parameter or nullif it does not exist. The return value is always a single String. It is up to the servlet to interpret the value. The GenericServletclass implements the ServletConfiginterface and thus provides direct access to the getInitParameter()method.* The method is usually called like this: public void init(ServletConfig config) throws ServletException { super.init(config); String greeting = getInitParameter(”greeting”); } A servlet that needs to establish a connection to a database can use its init parameters to define the details of the connection. We can assume a custom establishConnection()method to abstract away the details of JDBC, as shown in Example 4-1. * The servlet must call super.init(config)in its init()method to get this functionality. Example 4-1. Using init parameters to establish a database connection java.sql.Connection con = null; public void init(ServletConfig config) throws ServletException { super.init(config); String host = getInitParameter( host ); int port = Integer.parseInt(getInitparameter( port )); String db = getInitParameter( db ); String user = getInitParameter( user ); String password = getInitParameter( password ); String proxy = getInitParameter( proxy ); con = establishConnection(host, port, db, user, password, proxy); } Getting Init Parameter Names A servlet can examine all its init parameters using getInitParameterNames(): public Enumeration ServletConfig.getInitParameterNames() This method returns the names of all the servlet’s init parameters as an Enumerationof Stringobjects or an empty Enumerationif no parameters exist. It’s most often used for debugging. The GenericServletclass also makes this method directly available to servlets. Example 4-2 shows a servlet that prints the name and value for all of its init parameters.
Hint: This post is supported by Gama web hosting php mysql provider