Difference Between ServletContext and ServletConfig

ServletConfig: 

  • One ServletConfig Object is created per servlet
  • It can be used to access ServletContext
  • Parameters are configured in DD(deployment description)

ServletContext

  • One ServletContext will be created per web application.
  • Can be used to access web app parameter.
  • Can be used to get server Info.

In Java web development, both ServletContext and ServletConfig are important components, but they serve different purposes within the servlet architecture.

  1. ServletContext:
    • Scope: It represents the entire web application and is common to all servlets in that application.
    • Initialization Parameters: It can hold initialization parameters that are shared among all servlets in the web application.
    • Attributes: It provides a way to share attributes (objects) between different components of the web application, such as servlets, filters, and listeners.
    • Lifetime: The ServletContext is created when the web application is deployed and destroyed when the web application is undeployed.
  2. ServletConfig:
    • Scope: It represents the configuration for a specific servlet.
    • Initialization Parameters: It holds initialization parameters specific to a particular servlet.
    • Attributes: It doesn’t provide a way to share attributes between different servlets; that’s the role of the ServletContext.
    • Lifetime: The ServletConfig is created when a servlet is initialized and is destroyed when the servlet is taken out of service.

In summary, ServletContext is for global information that needs to be shared across all components of a web application, while ServletConfig is specific to a particular servlet and holds configuration information for that servlet. The ServletContext is often used for context-wide settings, such as database connection information or other global parameters, while the ServletConfig is used for configuration specific to the behavior of a particular servlet.