Reputation: 2730
I'm developing a web app using JavaEE. My question is about which is the best practice to use global config parameters that I could use from every Servlet or JSP page.
I have this two possibilities:
1. Using web.xml file and its context-param values, like:
<context-param>
<param-name>myParam</param-name>
<param-value>theValue</param-value>
</context-param>
and then retrieve the values in this way:
String data = getServletConfig().getServletContext().getInitParameter("myParam");
2. Using a .properties file that would be read by a singleton class with static attributes. The config file would be something like:
myParam=theValue
and the class:
public class Config {
private final static String FILE_CONFIG = "/WEB-INF/config.properties";
private static String myParam = null;
// more properties
// singleton constructor and init attributes
public static String getMyParam() {
return myParam;
}
// more getters
}
So I use it in this way:
String data = utils.Config.getMyParam();
All in all, which option do you think is the best practice to develop? The first, the second, maybe another one...?
Thanks in advance!
Upvotes: 1
Views: 391
Reputation: 1964
I will agree with @kolossus. Though both the methods are acceptable, using context-param values of web.xml is more preferable for following reasons:
Though both methods can handle data almost equally efficiently, web.xml file is the preferred option when it comes to complex data.
When we talk of complex data, interpreting the same correctly should also be easy. web.xml allows you to have data in hierarchical order and if required, maintaining a parent-child relationship.
e.g: In Vehicles, we have two-wheeler and four-wheeler. In two-wheeler we again have bikes and scooter. In scooter we have Vespa. In bikes we again have economy-bike and sportsbike.
<vehicle>
<two-wheeler>
<scooter>Vespa</scooter>
<bike>
<eco-bike>Hero</eco-bike>
<sportsbike>Ducati</sportsbike>
</bike>
</two-wheeler>
</vehicle>
Representing above data in .properties file might become a bit clumsy.
It is in XML format. Hence your content can be used across different systems. XML file comes with character-encoding which allows different systems to understand how to interpret this particular file.
The same is not the case with .properties file. You will have to encode it specifically for the target system. Again it comes with the risk of data corruption on the other end.
For all these reasons(& probably few more), using web.xml file and its context-param values is recommended.
Upvotes: 1