Java.Servlet.Why is it necessary to override only the init() method without arguments?

🧠 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 GenericServlet or HttpServlet
  • You want to skip calling super.init() (not recommended)
  • You’re doing something very custom or low-level

✅ TL;DR

MethodOverride?Why?
init(ServletConfig config)❌ RareAlready handled by superclass (GenericServlet)
init()✅ CommonClean, simple, gets called automatically
This entry was posted in Без рубрики. Bookmark the permalink.