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
| Feature | ServletConfig | ServletContext |
|---|---|---|
| Scope | Per servlet | Per web application |
| Purpose | Pass init parameters to a specific servlet | Share data and resources across all servlets |
| Defined In | Inside <servlet> tag in web.xml | Inside <context-param> tag in web.xml |
| Accessed By | getServletConfig() | getServletContext() |
| Common Use | DB name for one servlet, file path, etc. | Logging config, app version, global file paths, etc. |
| Lifecycle | Exists as long as the servlet is loaded | Exists as long as the web app is running |
| Sharing | Not shared between servlets | Shared 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
ServletConfigfor servlet-specific setup. - Use
ServletContextfor 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
