If you have two servlets, the servlet container will create two separate ServletConfig
instances — one for each servlet.
🧠 Why?
Because ServletConfig
is meant to hold configuration specific to one servlet, such as:
- Init parameters defined in
<servlet>
tag or@WebServlet
- The servlet’s name
- A reference to the shared
ServletContext
Each servlet can have its own initialization settings — so it needs its own ServletConfig
object.
🔧 Example
web.xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.app.LoginServlet</servlet-class>
<init-param>
<param-name>loginDb</param-name>
<param-value>jdbc:mysql://login-db</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>AdminServlet</servlet-name>
<servlet-class>com.app.AdminServlet</servlet-class>
<init-param>
<param-name>adminDb</param-name>
<param-value>jdbc:mysql://admin-db</param-value>
</init-param>
</servlet>
Servlets
public class LoginServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
String db = config.getInitParameter("loginDb");
System.out.println("LoginServlet using DB: " + db);
}
}
public class AdminServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
String db = config.getInitParameter("adminDb");
System.out.println("AdminServlet using DB: " + db);
}
}
✅ Each servlet gets its own ServletConfig
instance, containing only its own init parameters.
🔁 What About ServletContext
?
- Only one
ServletContext
per web application - Shared among all servlets, filters, and listeners
✅ Summary
Concept | Scope | One per… |
---|---|---|
ServletConfig | Per servlet | ✅ Yes |
ServletContext | Per web app | ❌ No (only one) |