Difference between ServletConfig and ServletContext

Both ServletConfig and ServletContext are configuration objects used by servlet container to initialize various init parameters for a web application. However they differ in terms of the scope and availability of init parameters defined by both of them.

Init Parameters in deployment descriptor (web.xml)

Init parameters for ServletConfig are defined within <servlet> element for each specific servlet.
 <!-- other stuff -->
Init parameters for ServletContext are defined within the <web-app> element but NOT within a specific <servlet> element.
 <!-- other stuff including servlet declarations -->
Servlet Code

getServletConfig().getInitParameter("foo"); for ServletConfig
getServletContext().getInitParameter("foo"); for ServletContext


There's only one ServletContext for an entire web app, and all the parts of the web app share it. Hence parameters required by all the servlets should be configured within ServletContext. For example database connection parameters.

But each servlet in the app has its own ServletConfig. Hence the parameters, needed by a particular servlet but should not be accessed by other servlets, should be configured by ServletConfig.

The Container makes a ServletContext when a web app is deployed, and makes the context available to each Servlet and JSP (which becomes a servlet) in the web app.

No comments:

Post a Comment