Java Web Applications – Using Constants.java Class vs Context Param in Servlet

javaweb-applications

I'm just wondering whether to keep some of my variables in Constants class or keep it in web.xml

Say, I want to keep a variable of Facebook graph API prefix or api_key, client_id

From my understand, the difference between Constants.java and web.xml is web.xml is easier to rewrite on compile using ant.

So, you can replace your variables in web.xml according to what environment you are building you app for. (client_id varies by development environment/production environment, for example)

If I understand it right, then Facebook graph API prefix should be kept in Constants.java (because it always is "https://graph.facebook.com/") and api_key, client_id should be kept in web.xml?

What's the proper way to use them?

Best Answer

In your scenario, these values are best kept in properties file. Create a properties file in classpath and read it at your application startup to instantiate the values. Or you can read them fresh for each request, if they tends to change. Java provides very easy way for reading/writing properties file with Properties class.

You can also externalize the properties file if you want. i.e. put them into user home directory to make them completely independent. Think of it, when you change the value and the running application takes the new value without re-build or even re-deployment.

Related Topic