Fetching parameters from web.xml
by, 05-24-2011 at 01:30 PM (3629 Views)
The file named web.xml is part of your web applications. You may use it for different purpose. Sometimes you wish to define some parameters for your web application in it. Obviously, you need to use this in your application. I will briefly tell you how to do this.
At first, let me give you an example. We have a web application that needs to send its id and license code to some authentication server before doing some business operation. The id and license code are static and you may wish to define these as static final in your code:
Well, it will work but this info might change in future. Also assume that the web application will be deployed at different locations with different appId and license info. Its better to define these in some config file. The ideal choice will be web.xmlJava Code:public static final String appId = "dublin14"; public static final String license = "3KK838483";
Now we have defined the parameters in web.xml. This file will reside under WEB-INF. Now lets see how to fetch these values.Java Code:<web-app> <display-name>testwebapp</display-name> <context-param> <param-name>appId</param-name> <param-value> dublin14</param-value> </context-param> <context-param> <param-name>license</param-name> <param-value> 3KK838483</param-value> </context-param> </web-app>
We need to use ServletContext (javax.servlet.ServletContext) to fetch the required value:
If you have a java bean where you need to fetch the parameters, then simply pass the ServletContext as an argument from JSP/Servlet to the bean.Java Code:String appId = context.getInitParameter("appId"); String license = context.getInitParameter("license");
Getting back to our example scenario, after getting the parameters, simply call the required method on authentication server with appId and license info. How to do that: webservices, RMI, Corba ...
Hope this helps.