Before going ServletContext Example, see the difference between <init-param> and <context-param>, both written in web.xml file.
What is <init-param>?
portnumber
8888
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.
goldrate
3100.5
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
Welcome to Tomcat
Welcome to Tomcat
goldrate
3100.5
klm
ContextReading
klm
/conread
Servlet Program: ContextReading.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ContextReading extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// reading gold weight from client file, ClientData.html
String gold = req.getParameter("t1");
int gw = Integer.parseInt(gold);
// reading gold rate from of web.xml file
ServletContext sc1 = getServletContext();
String rate = sc1.getInitParameter("goldrate");
double gr = Double.parseDouble(rate);
// estimate and make bill
double total = gw * gr;
out.println("Your Gold Purchase Information:
");
out.println("Gold Weight: " + gw + " gms.
");
out.println("Gold Rate Rs." + gr + "/gm.
");
out.println("To pay Rs." + total);
out.close();
}
}
Following is the client Screen: ClientData.html
Output screen when submit is clicked after entering gold weight.
Screenshot of ServletContext Example