In this section we will discuss about the ServletContext simple example.
Servlet Context Example
In this section we will discuss about the ServletContext simple example.
In this example I used some methods of the ServletContext interface. Through which we can easily understand the basic of Servlet Context. Methods that are used in are :
getInitParameter();
getInitParameterNames();
getMajorVersion();
getMinorVersion();
getServerInfo();
Meaning/Work of all the methods described above are clear by their names.
Example : ServletContextExmaple.java
import java.util.Enumeration; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletContextExample extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter pw = res.getWriter(); ServletContext cntxt = getServletContext(); pw.println("Servlet Context are : "); Enumeration enmparam = (Enumeration) cntxt.getInitParameterNames(); while (enmparam.hasMoreElements()) { pw.println(enmparam.nextElement() + ", "); } pw.println(""); pw.println("Name = " + cntxt.getInitParameter("Name")); pw.println("Age = " + cntxt.getInitParameter("Age")); String s = cntxt.getContextPath(); pw.println("Context Path = " + s); int a = cntxt.getMajorVersion(); pw.println("Major Version = " + a); int b = cntxt.getMinorVersion(); pw.println("Minor Version = " + b); String info = cntxt.getServerInfo(); pw.println("I am working currently on the server " + info); } }
Output : When you will execute this program the output will be displayed as :
[ 0 ] Comments