Technically, yes, you can define a constructor in a servlet, but…
⚠️ You Should Avoid Putting Initialization Logic in It.
Here’s why:
🚫 Why Not Use Constructor for Initialization?
- Servlet container controls instantiation — not you.
- ServletConfig and ServletContext are not available during constructor execution.
- Servlet lifecycle methods (like
init()
) are designed for this exact purpose. - You can’t throw
ServletException
orIOException
from a constructor — which you might need during initialization.
✅ Correct Way: Use the init()
Method
public class MyServlet extends HttpServlet {
private DatabaseConnection db;
@Override
public void init() throws ServletException {
super.init();
db = new DatabaseConnection("url", "user", "pass");
System.out.println("Servlet initialized.");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
db.query("SELECT * FROM users");
res.getWriter().write("Handled with initialized DB");
}
}
🛠️ Bonus: Reading Config Params from web.xml
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
<init-param>
<param-name>dbHost</param-name>
<param-value>localhost</param-value>
</init-param>
</servlet>
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
String dbHost = config.getInitParameter("dbHost");
// Use dbHost for your setup
}
✅ Summary
Method | Purpose | Recommended? |
---|---|---|
Constructor | Just calls super() ; avoid init logic | ❌ No |
init() | Lifecycle-aware, has access to config/context | ✅ Yes |
init(ServletConfig) | Useful if you want to access params | ✅ Yes |
🧠 Rule of Thumb:
Use
init()
for all servlet initialization.
Use constructor only if you absolutely must create a field early — but not for real setup logic.