This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hello , Being completely new to servlet programming I would like to clarify something, according to "Head first Servlets and JSP" the best way to access initialization data for a servlet is to access it through the servletContext. I know this data will be accessible to all the threads. Now suppose instead of placing the string "E-mail" and associating the text "firstname.lastname@example.org" to that text in the servtContext. I could might as well have created a POJO object such as this
private: String Email;
so all my servlets had to do was create an instance of this object and read it. Would'nt it be the same thing ?? I know we couldnt write to it (unless i made it a singleton) since the instances of the object wouldnt be shared. But incase some data needs to be read only ... so whats the difference?
Not too much, except for the fact that in case you need to update the address - you need to change the class, compile the class and re-deploy as opposed to a property change and redeploy.
Also in many real world scenario, the servlet config files are 'environment-specific' so for example in your development environment you email property could be email@example.com while in production it could be firstname.lastname@example.org
In general putting initialization properties in ServletConfig.xml has a few more advantages/uses.
1. Frameworks (like spring) pick up certain properties against well defined names
2. Initialization date is more readable rather than scattered around in different classes.
ServletContext is live until your web application exist! session, request may share the object! remember there is a one servletcontext per an application. for instance you may have datasource in servletcontext
Seetharaman Venkatasamy wrote: for instance you may have datasource in servletcontext
I don't think it is a really good idea. The context stays live as long as the application stays live, for many applications this would mean until the server is brought down of maintenance. So context is not the best place to have datasource object.