Java: ServletConfig vs ServletContext

Here’s a clear and copyright-free comparison of ServletConfig vs ServletContext — perfect for learning or blogging.


🔄 ServletConfig vs ServletContext in Java

Both ServletConfig and ServletContext are part of the Java Servlet API and provide access to configuration data, but they serve different scopes and purposes.


📋 Comparison Table

FeatureServletConfigServletContext
ScopePer servletPer web application
PurposePass init parameters to a specific servletShare data and resources across all servlets
Defined InInside <servlet> tag in web.xmlInside <context-param> tag in web.xml
Accessed BygetServletConfig()getServletContext()
Common UseDB name for one servlet, file path, etc.Logging config, app version, global file paths, etc.
LifecycleExists as long as the servlet is loadedExists as long as the web app is running
SharingNot shared between servletsShared by all servlets in the app

🧪 Example Usage

🔹 web.xml

<!-- ServletConfig (specific to one servlet) -->
<servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>com.example.MyServlet</servlet-class>
    <init-param>
        <param-name>dbName</param-name>
        <param-value>students</param-value>
    </init-param>
</servlet>

<!-- ServletContext (shared across servlets) -->
<context-param>
    <param-name>appVersion</param-name>
    <param-value>1.2.3</param-value>
</context-param>

🔹 In Servlet Code

public class MyServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // ServletConfig example
        ServletConfig config = getServletConfig();
        String dbName = config.getInitParameter("dbName");

        // ServletContext example
        ServletContext context = getServletContext();
        String appVersion = context.getInitParameter("appVersion");

        response.getWriter().println("DB: " + dbName + ", App Version: " + appVersion);
    }
}

✅ Summary

  • Use ServletConfig for servlet-specific setup.
  • Use ServletContext for application-wide configuration and shared data.

Let me know if you want:

  • 📝 A Markdown or HTML version
  • 📄 A downloadable PDF version
  • 🎯 Real-world examples (like uploading files, database configs) using context/config.

Ref: OpenAI/ChatGPT