What is the difference between ServletContext.getInitParameter() and HttpServlet.getInitParameter()?

André Wolf

[Original Question:

I am using Tomcat Web server.I am passing parameter in Web.xml using

<context-param>
<param-name>server</param-name>
<param-value>xxxxxxx</param-value>
</context-param>
But when I am calling getInitParameter("server") in init method it is returning null value. How to resolve this? ]

The <context-param> tag is used to set an init parameter for the whole application context, it is accessible by all Servlets and JSPs. You have to use getInitParameter() of javax.servlet.ServletContext, not the similar method found in HttpServlet. Just try the following method call in your servlet, it should return the correct parameter:

getServletContext().getInitParameter("server")

Alternatively, you can set an init parameter for a specific Servlet, it will only be accessible by this Servlet:

<web-app>
  <servlet> 
    <servlet-name>myservlet</servlet-name>
    <servlet-class>org.myorg.MyServlet</servlet-class>
    <init-parameter>
      <param-name>server</param-name>
      <param-value>xxxxxxx</param-value>
    </init-parameter>
  </servlet>

  ...
</web-app>

To retrieve this parameter you just call getInitParameter() in your servlet.

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.