0

I was reading a book about Servlet and the book used context-param and init-param, but he did not provide an example of how to use it. He just explain it in few words. Can some one give me example about how to use it and why I need it in my xml file?

NOTE: I am not talking about servlet-name and servlet-class. I am talking about the other two param.

<context-param>
    <param-name>custEmail</param-name>
    <param-value>isadfj@gmail.com</param-value>
</context-param>

<servlet>
    <servlet-name>addEmailListServlet</servlet-name>
    <servlet-class>email.addEmailListServlet</servlet-class>
    <init-param>
        <param-name>reletivePathFile</param-name>
        <param-value>/WEB-INF/Email.txt</param-value>
    </init-param>
</servlet>
Rawa
  • 33
  • 1
  • 5
loverBoy
  • 125
  • 2
  • 13

2 Answers2

1

They are initial parameter, you would get them with init(c:ServletConfig):void method, where once container instantiate the servlet, it will invoke init method and include the initial parameter provided by web.xml file to the instance.

So they do no do any magic, or anything, just initial parameter, they are very useful when something need to be configed at the start of servlet life, for example default email, or pool size, or external path name, anything.

for instance

<init-param>
    <param-name>sys_mail</param-name>
    <param-value>root@my-daemon.com</param-value>
</init-param>

And where the servlet

public void init(ServletConfig c) throws ServletException{
        c.getInitParameter("sys_mail");//this will return root@my-daemon.com
    }
1

Since you are Sending InitParameterRequest From Servlet Like

 this.myParam = servletConfig.getInitParameter("myParam");

then for Access this we can mapped on Web.xml like :-

<init-param>
    <param-name>myParam</param-name>
    <param-value>paramValue</param-value>
 </init-param>

Coming on Context Parameters Side . here we passed request on Servlet :

String myContextParam =request.getSession().getServletContext().getInitParameter("myParam");

Then for Access myContextParamwe can mapped on web.xml like :-

<context-param>
<param-name>myParam</param-name>
<param-value>the value</param-value>
</context-param>
Anand Dwivedi
  • 1,452
  • 13
  • 23