ServletConfig is a special interface in the Servlet API that allows the servlet container to pass configuration information to a servlet at initialization time.
You can think of it as the servlet’s own private config object, defined in web.xml (or annotation-based equivalent).
📦 What is ServletConfig?
- Part of
javax.servlet - Passed to the servlet by the container when calling
init(ServletConfig config) - Contains:
- Init parameters (name-value pairs defined in
web.xml) - Servlet name
- Reference to the ServletContext
- Init parameters (name-value pairs defined in
🧪 Example Use Case
📄 In web.xml:
<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:3306/mydb</param-value>
</init-param>
</servlet>
🧑💻 In Servlet:
public class MyServlet extends HttpServlet {
private String dbUrl;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config); // Important to call this!
dbUrl = config.getInitParameter("dbUrl");
System.out.println("Database URL: " + dbUrl);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.getWriter().write("Using DB URL: " + dbUrl);
}
}
You can also get it via getServletConfig() inside init() or doGet() if you’ve overridden the no-arg init() instead.
✅ Key Methods in ServletConfig
| Method | Description |
|---|---|
getInitParameter(String name) | Get a single init param |
getInitParameterNames() | Get all param names |
getServletName() | Get the name of the servlet |
getServletContext() | Get reference to global ServletContext |
🔁 ServletConfig vs ServletContext
| Feature | ServletConfig | ServletContext |
|---|---|---|
| Scope | Per servlet | Entire web application |
| Purpose | Config for a single servlet | Shared app-wide data & context |
| Defined in | <servlet> tag | <context-param> tag |
| Access from servlet | getServletConfig() | getServletContext() |
✅ Summary
| Feature | Description |
|---|---|
| What is it? | Config object passed to servlet during initialization |
| Where defined? | In web.xml or annotations (@WebServlet, etc.) |
| Purpose | Provide servlet-specific init parameters |
| Access how? | init(ServletConfig config) or getServletConfig() |
| Difference from context | Only for this servlet; not shared like ServletContext |