What is the difference between ServletContext and ServletConfig?

Ryan Breidenbach

A ServletContext represents the context in a servlet container of a servlet instance operates. A servlet container can have several contexts (or web applications) at one time. Each servlet instance is running in one of these contexts. All servlets instances running in the same context are part of the same web application and, therefore, share common resources. A servlet accesses these shared resource (such as a RequestDispatcher and application properties) through the ServletContext object.

This notion of a web application became very significant upon the Servlet 2.1 API, where you could deploy an entire web application in a WAR file. For more specifics on web application, please see this FAQ.

Notice that I always said "servlet instance", not servlet. That is because the same servlet can be used in several web applications at one time. In fact, this may be common if there is a generic controller servlet that can be configured at run time for a specific application. Then, you would have several instances of the same servlet running, each possibly having different configurations.

This is where the ServletConfig comes in. This object defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig.

See also What is a Servlet Context?.