It is a interface which provides set of method to communicate with servlet container.
For a web application their will be one context.
It is contained with in ServletConfig Object
Way 1: Using Config
ServletConfig conf = getServletConfig(); ServletContext context = conf.getServletContext();
Way 2: Using context method from GenericServlet class
ServletContext ctx = getServletContext();
Way 3: Using HttpRequest Object
ServletContext ctx = req.getServletContext();
1) Variable initialized in web.xml:
<context-param> <param-name>test</param-name> <param-value>done</param-value> </context-param>
We can get this parameter value in Servlet as:
String str = context.getInitParameter("test");
2) We can also set and get attributes using ServletContext.
e.g: Set the value in one servlet and get in another
ServletOne
ServletContext ctx = getServletContext(); ctx.setAttribute("test","done");
ServletTwo
ServletContext ctx = getServletContext(); String str = ctx.getAttribute("test");
3) To get RequestDispatcher Object(to transfer the control from one servlet to another servlet\jsp etc)
RequestDispatcher reqDispObj = getServletContext() .getRequestDispatcher("/rootpath/home.jsp");