Java.Servlet.What is ServletConfig?

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

🧪 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

MethodDescription
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

FeatureServletConfigServletContext
ScopePer servletEntire web application
PurposeConfig for a single servletShared app-wide data & context
Defined in<servlet> tag<context-param> tag
Access from servletgetServletConfig()getServletContext()

✅ Summary

FeatureDescription
What is it?Config object passed to servlet during initialization
Where defined?In web.xml or annotations (@WebServlet, etc.)
PurposeProvide servlet-specific init parameters
Access how?init(ServletConfig config) or getServletConfig()
Difference from contextOnly for this servlet; not shared like ServletContext
This entry was posted in Без рубрики. Bookmark the permalink.