File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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 "" to that text in the servtContext. I could might as well have created a POJO object such as this
class Pojo
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?
Saifuddin Merchant
Ranch Hand

Joined: Feb 08, 2009
Posts: 607

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 while in production it could be

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

Joined: Jun 06, 2007
Posts: 2851

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.

|Asking Good Questions|
I agree. Here's the link:
subject: Why use ServletContext?
It's not a secret anymore!