View RSS Feed

My Java Tips

Fetching parameters from web.xml

Rate this Entry
by , 05-24-2011 at 01:30 PM (3276 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:

Java Code:
public static final String appId  = "dublin14";
public static final String license  = "3KK838483";
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.xml

Java Code:

<param-value> dublin14</param-value>

<param-value> 3KK838483</param-value>

Now we have defined the parameters in web.xml. This file will reside under WEB-INF. Now lets see how to fetch these values.

We need to use ServletContext (javax.servlet.ServletContext) to fetch the required value:

Java Code:
String appId = context.getInitParameter("appId");
String license = context.getInitParameter("license");
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.

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.

Submit "Fetching parameters from web.xml" to Facebook Submit "Fetching parameters from web.xml" to Digg Submit "Fetching parameters from web.xml" to Submit "Fetching parameters from web.xml" to StumbleUpon Submit "Fetching parameters from web.xml" to Google

Updated 05-24-2011 at 01:34 PM by Java Tip

JSP , Servlet , XML