aspose file tools*
The moose likes Servlets and the fly likes Why use ServletContext? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Why use ServletContext?" Watch "Why use ServletContext?" New topic
Author

Why use ServletContext?

Rajesh Khan
Ranch Hand

Joined: Oct 16, 2011
Posts: 230
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 "email@yahoo.com" to that text in the servtContext. I could might as well have created a POJO object such as this
class Pojo
{
private: String Email;
Pojo{Email="some@yahoo.com"}
}

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?
Saifuddin Merchant
Ranch Hand

Joined: Feb 08, 2009
Posts: 606

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 developers@domain.com while in production it could be production@domain.com

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.


Cheers - Sam.
Twisters - The new age Java Quiz || My Blog
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

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
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

and Welcome to JavaRanch
Amit Ghorpade
Bartender

Joined: Jun 06, 2007
Posts: 2716
    
    6

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.

SCJP, SCWCD.
|Asking Good Questions|
 
 
subject: Why use ServletContext?