ServletConfig and ServletContext
ServletConfig holds configuration for a single Servlet, while ServletContext provides application-wide scope shared by all Servlets in the web application.
ServletConfig
Each Servlet has its own ServletConfig object, available via getServletConfig() or the init() method. Use it to read init parameters defined in web.xml or @WebInitParam annotations specific to that Servlet.
ServletContext
ServletContext represents the entire web application. There is one instance per application. Use it to store shared resources (database connection info, file paths), read context init parameters, get real paths to files, and log application events.
Reading Init Parameters
// Servlet-specific (ServletConfig)
String dbUrl = getServletConfig().getInitParameter("db.url");
// Application-wide (ServletContext)
String appName = getServletContext().getInitParameter("app.name");
getServletContext().setAttribute("userCount", 0);Scope Comparison
- Request scope — One request (request.setAttribute).
- Session scope — One user session (session.setAttribute).
- Application scope — All users, entire app (context.setAttribute).
- ServletConfig scope — One Servlet only (init parameters).
Frequently Asked Questions
Is ServletContext thread-safe?▼
The ServletContext object itself is thread-safe, but attributes you store in it are not automatically synchronized. Use concurrent collections or synchronization when multiple threads modify shared context attributes.
