3

I need to retrieve init-param value from xml to Servlet i used following code

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>LoginServlet</servlet-class>
    <init-param>
        <param-name>jdbcDriver</param-name>
        <param-value>com.mysql.jdbc.Driver</param-value>
    </init-param>
</servlet>

servlet code

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    System.out.println(config.getInitParameter("jdbcDriver"));
}

But It displayed null .. could any one help me to do that . thanks in advance

4 Answers 4

4

I can't see a single reason, why you have to override your init(ServletConfig sc) method, since you can always get your ServletConfig by calling your inherited getServletConfig() method.

System.out.println(getServletConfig().getInitParameter("jdbcDriver"));
2

If you have custom initialization work to do, override the no-arg init() method, and forget about init(ServletConfig). Is it ok to call getServletConfig() method inside the no-arg init() method? Yes, an instance of ServletConfig has already been saved by superclass GenericServlet.

http://javahowto.blogspot.com/2006/06/common-mistake-in-servlet-init-methods.html

It is always good to use packages for classes. It enables clear demarcation.

0

um... it should work. Are you calling the code in LoginServlet? And the

<servlet-class>LoginServlet</servlet-class> 

is not in any package?

0

First of all you have to specify <inin-param></init-param> in web.xml file:

<init-param>
    <param-name>jahnvi</param-name>
    <param-value>abac</param-value>
</init-param>

And you have to specify code in servlet:

out.println("<h2>Init Parameters:</h2>");
Enumeration<String> initParams = getServletConfig().getInitParameterNames();
while (initParams.hasMoreElements()) 
{
    String paramName = initParams.nextElement();
    String paramValue = getServletConfig().getInitParameter(paramName);
    out.println(paramName + ": " + paramValue + "<br>");
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.