ServletContext Example context-param

ServletContext Example context-param

Before going ServletContext Example, see the difference between <init-param> and <context-param>, both written in web.xml file.

What is <init-param>?

We have seen the above code in Servlet web xml init param Example using ServletConfig where the "portnumber" and "8888" are accessible for the particular servlet "ReadInitParamValues". Other servlets in the container cannot access this data. That is, the <init-param> is accessible to one servlet only or it can be said the <init-param> data is private for a particular servlet.

What is <context-param>?

Now is there anyway, the data of <init-param> is accessible to all the servlets under execution in the container? Yes, there exists; we write the <init-param> outside of any <servlet> tag in the same web.xml file. For this, <context-param> (instead of <init-param>) is used as follows.

Because the tag <context-param> exists, in the web.xml, outside any servlet tag (say, global area), every servlet can access it.

Finally, <init-param> data is local for a particular servlet and context-param data is global for all servlets. This is the difference between <init-param> and <context-param>.

Following ServletContext Example illustrates

The aim of this program is the servlet reads the weight of gold article from the client HTML file and the gold rate from <context-param> and estimates the bill amount payable.

Client Program: ClientData.html

web.xml entry for the Servlet

Servlet Program:

Following is the client Screen: ClientData.html


Output screen when submit is clicked after entering gold weight.

Screenshot of ServletContext Example

6 thoughts on “ServletContext Example context-param

  1. Pankaj Bisaria

    Hello Mr Rao,

    What you think the Gold rate should be kept as a context parameter? What happened if the gold rate got change? Do we need to restart the application to reflect the new rate?

  2. Sridhar

    Hi sir,

    I read ServeletContext interface explanation, there it is mentioned we create ServletContext object through ServletConfig object. i.e.,

    ServletConfig config1 = getServletConfig();
    ServletContext context1 = config1.getServletContext();

    But in the above example the object for ServletContext is created as below
    ServletContext sc1 = getServletContext();
    without ServletConfig object creation.

    though i have not executed the above code. Can you please confirm whether ServletContext object is created through ServletConfig object or directly as the code mentioned in the above example.

Leave a Reply

Your email address will not be published. Required fields are marked *