🧠 There Are Two init() Methods in Servlets:
public void init(ServletConfig config) throws ServletException
public void init() throws ServletException
📌 So… why is it usually enough (and preferred) to override only the no-arg init()?
Here’s the Explanation:
1. Servlet API Design Handles ServletConfig for You
If your servlet extends HttpServlet, then the base class (GenericServlet) already overrides:
public void init(ServletConfig config) throws ServletException {
this.config = config;
init(); // calls the no-arg version
}
So when the servlet container calls init(ServletConfig config), it:
- Stores the config in the
GenericServlet - Then delegates to your overridden no-arg
init()
✅ This allows you to override only:
@Override
public void init() throws ServletException {
// Initialization logic here
}
Without worrying about ServletConfig, unless you explicitly need it.
2. You Can Still Access ServletConfig Inside No-Arg init()
Even in the no-arg method, you can do:
String value = getServletConfig().getInitParameter("some-param");
So you lose nothing, but keep your code cleaner.
🤔 When Would You Override the init(ServletConfig config) Version?
Rarely. Only when:
- You’re not extending
GenericServletorHttpServlet - You want to skip calling
super.init()(not recommended) - You’re doing something very custom or low-level
✅ TL;DR
| Method | Override? | Why? |
|---|---|---|
init(ServletConfig config) | ❌ Rare | Already handled by superclass (GenericServlet) |
init() | ✅ Common | Clean, simple, gets called automatically |