ServletConfig vs. the ServletContext: Understanding the Difference
The ServletConfig and ServletContext are two members of the Servlet API that developers often confuse with one another, and sadly, because of the confusion, they often don’t take proper advantage of these objects.
The thing to remember is that the ServletConfig is a place in which String based name-value pairs, which are defined in the Servlet’s section of the web.xml file, can be accessed. The properties here can be shared amongst all users who invoke the Servlet in question. It’s not so much of a global property, as much as one that can be used by all users who invoke a given Servlet. Furthermore, the property remains the same for all users invoking the Servlet. The data will not change on a per user basis.
Contrast this with the ServletContext object. The ServletContext object is global and shared within a given web application or war file. Any artifact that is packaged within a war file can gain access to the data contained within ServletContext object. The ServletContext data is global to all users and all resources within the web application, and it is because of the scope that the ServletContext is also often referred to as the application context. Basically, it’s a scope that is global to the given web application. Furthermore, the ServletContext can contain name-value pairs in the form of both Strings and Object types.
So, when data specific to how a given Servlet should behave needs to be configured, configure that information in the ServletConfig object. When data needs to be shared with all users accessing a given application, place it in the ServletContext.
02 Oct 2011
Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.