Tuesday 3 April 2012

Initialization of parameter and reading parameters

1. Why should we use initialization Parameters ?

Ans:
  • While we are developing Web applications, we should provide some data into the servlet programs
  • Example: I'm developing a Login form as a part of my task, in the login application, i obtained the database connection by using the database user name and password (scott, tiger in my system)
  • But actual DB username and password are available only at the time of deploying the application. That means DB username and password changes (it totally depends on DBA).
  • If I give DB usernmae =scott, password=tiger in the servlet program , if I handover my task to the client, his username and password may be different
  • So again i have to change the servlet program and change the username and password according to client system username and password,(this is known as hadrcoding)
  • Instead of providing the database details (hard coding the data) in the Servlet, you can configure the data externally from the Servlet and then retrieve(inject) it into the servlet by using "Initialization Parameters" .
  • In other words (technically) the Servlet Container provides the ability to store startup and configuration information for a Servlet in the form of initialization parameters, this is called as "init parameters" and "context init parameters" are specific to all or multiple Servlet's configured in the deployment descriptor file.
Simple answer:
What is the purpose of the init-parameters?

=>whenever we need to supply different set of values to a servlet at different times of its deployment without changing its sourcecode ,we go for initparameters.

=>Initparameters ensure prevention of hardcoding of certain values in a servlet.

for e.g: database connection details.
 2. Advantages of Initialization Parameters

Ans:
  1.  To reduce the complexity code of the server-side program
  2.  To minimize the maintenance of web application to build successful in java .
Example:
  •      Suppose I have developed one web application, in the contact page, i have to give my phone number. To do this one in Servlet, i have to write the following code in my servlet:
  PrintWriter out=response.getWriter(); //creating the PrintWriter object
  out.println("mobile number: 999999986" );
  • For the above code, I have to recompile the Servlet every time if mobile number changes
  • Rather than hard-coding the mobile number directly into the Servlet's source code, I must always maintain the same mobile number (data value) in the deployment descriptor file (web.xml ), so that any changes in the mobile number does not affect the web application.
  • In Other words, I can pass the value of mobile number through the init parameter in the web.xml file.
3. Syntax for initialization parameters in the web.xml:

<servlet>
   <servlet-name>.....</servlet-name>
     <servlet-class>...</servlet-class>
         <init-param>
            <param-name>MobileNumber</param-name>
             <param-value>999999986</param-value>
        </init-param>
</servlet>

4. Accessing the initialization parameters from web.xml into servlet:

By using getInitParameter("MobileNumber");
             getInitParameterNames();

5. Example program for initialization parameters
//Home.html
<HTML>
<HEAD>
<TITLE> Servlet Examples (Init Parameters Example) </TITLE>
</HEAD>
<BODY>
<FORM ACTION="initParamsSer" method="get">
<INPUT TYPE="submit" value="Get Init Parameters Configured in DD file"/>
</FORM><br/>
</BODY>
</HTML>
//InitParamsServlet.java
package com.rajendra.servlets;

import javax.servlet.*;
import java.util.*;

public class InitParamsServlet extends GenericServlet 
{

public void init()throws ServletException {

//Test Code to demonstrate hot to get init parameters
//Here to demonstrate this we will print the name & values

//Getting the parameter value of the given name
String value=getInitParameter("Ram");//it is a predefined method, read the value of "Ram" in the web.xml file and returns its value
System.out.println("Ram Salary is : "+value);

//To get all the parameter values
System.out.println("Getting all the parameters");
System.out.println("----------------------");
System.out.println("Name \t Salary");
System.out.println("----------------------");
/*Enumeration is a interface used to store the elements and getInitParameterNames() is used to read the values
from the web.xml file and stores into en object */
Enumeration en=getInitParameterNames();
while (en.hasMoreElements()) //returns true if the elements are there in the enumeration, false otherwise

 {

String name=(String)en.nextElement();
value=getInitParameter(name);
System.out.println(name+"\t"+value);
}//while
}
public void service(ServletRequest req,ServletResponse res)
throws java.io.IOException,ServletException {

  res.setContentType("text/html");
  java.io.PrintWriter out=res.getWriter();
out.println("<html><body>");
/*
As described like Initialization parameters are available to the servlet at any time i.e. in initialization, servicing the client and destroying.
*/
 
//Getting the parameter value of the given name

String value=getInitParameter("name");

out.println("Ravi salary is : <b>"+value+"</b><br/>");


//To get all the parameter values
out.println("Getting all the parameters<br/>");
out.println("<table border='1'>");
out.println("<tr><th>Name</th>");
// out.println("<th>Value</th></tr>");
out.println("<th>salary</th></tr>");
Enumeration en=getInitParameterNames();
while (en.hasMoreElements()){

String name=(String)en.nextElement();
String salary=getInitParameter(name);
out.println("<tr><td>"+name+"</td>");
// out.println("<td>"+value+"</tr>");
out.println("<td>"+salary+"</tr>");
}//while
out.println("</table>");
out.println("</body></html>");
  }//service
}//class
/*
D:\webtechnologies\servlets\\initParams>javac -d . InitParamsServlet.java
*/
//web.xml
<?xml version="1.0"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>myser</servlet-name>
<servlet-class>
com.servlets.InitParamsServlet
</servlet-class>
<init-param>
<param-name>Ram</param-name>
<param-value>20000</param-value>
</init-param>
<init-param>
<param-name>Ravi</param-name>
<param-value>30000</param-value>
</init-param>
<init-param>
<param-name>Rajesh</param-name>
<param-value>40000</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myser</servlet-name>
<url-pattern>/initParamsSer</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Home.html</welcome-file>
</welcome-file-list>
</web-app>

You may like the following posts:

No comments:

Post a Comment