Java.Servlet.What is the difference between ServletContext and ServletConfig?

Both ServletContext and ServletConfig are part of the Servlet API, but they serve different scopes and purposes. Let’s break them down side by side 👇

🧠 Core Difference

FeatureServletConfigServletContext
ScopeOne servlet onlyEntire web application
PurposePasses init parameters to a specific servletShares global configuration and resources
Data sharing❌ Not shared across servlets✅ Shared across all servlets and filters
Defined in<servlet> tag in web.xml or @WebServlet<context-param> tag in web.xml or via listener
Accessed viagetServletConfig()getServletContext()
LifecycleCreated per servletCreated once per application
Typical use caseRead servlet-specific config like db URLShare app-wide info like version, cache, shared objects

📄 Example: web.xml with Both

<context-param>
  <param-name>appVersion</param-name>
  <param-value>1.0.0</param-value>
</context-param>

<servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>com.myapp.MyServlet</servlet-class>
  <init-param>
    <param-name>dbUrl</param-name>
    <param-value>jdbc:mysql://localhost/mydb</param-value>
  </init-param>
</servlet>

🔧 Accessing Values in Servlet

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    // From ServletConfig (specific to this servlet)
    String dbUrl = config.getInitParameter("dbUrl");

    // From ServletContext (shared by all servlets)
    String version = config.getServletContext().getInitParameter("appVersion");
}

Or in modern style (if you override init() without arguments):

String dbUrl = getServletConfig().getInitParameter("dbUrl");
String version = getServletContext().getInitParameter("appVersion");

🧪 ServletConfig vs ServletContext: Analogy

AnalogyServletConfigServletContext
👤 Per-employee dataTheir desk nameplateCompany-wide notice board
📦 Per-component configYour specific component’s configApp-level shared resources and settings

✅ Summary

Key PointServletConfigServletContext
For what?One specific servletEntire application
Shared?❌ No✅ Yes
Common usageRead servlet init parametersRead global parameters or share data
Who creates it?Container (one per servlet)Container (one per app)
This entry was posted in Без рубрики. Bookmark the permalink.