1

What is the use of init-param tag? in web.xml reagarding servlet and jsp?

<servlet>  
<servlet-name>sonoojaiswal</servlet-name>  
<jsp-file>/welcome.jsp</jsp-file>  

<init-param>  
<param-name>dname</param-name>  
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
</init-param>  

</servlet>  

<servlet-mapping>  
<servlet-name>sonoojaiswal</servlet-name>  
<url-pattern>/welcome</url-pattern>  
</servlet-mapping>  

</web-app>  

3 Answers 3

3

We can pass parameters to our servlet from the web.xml file using init param's. Here's a small example.

web.xml:

<servlet>
        <description></description>
        <display-name>Test</display-name>
        <servlet-name>Test</servlet-name>
        <servlet-class>servlets.Test</servlet-class>
        <init-param>
            <param-name>dname</param-name>
            <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>Test</servlet-name>
        <url-pattern>/Test</url-pattern>
    </servlet-mapping>

Servlet:

PrintWriter printWriter = response.getWriter();
printWriter.println(getServletConfig().getInitParameter("dname"));

Output:

enter image description here

You will find an excellent answer by informatik01 on this subject here.

3

You can see that init-param is defined inside a servlet element. This means it is only available to the servlet under declaration and not to other parts of the web application. You can use that particular parameter in only this Servlet not in others. you can access it by ServletConfig object also

servletConfig.getInitParameter("dname");
1

They are called Servlet init parameters (defined in element)

Servlet init parameters are defined within the element for each specific servlet.

They are specific to each servlet.They are available in the init method of the servlet as arguments. this will be used for initial loading of values in the servlet.

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