context – circumstances that form the setting for an event.For our scenario context represents virtual host within which our web application runs.The environment where the WAR file is deployed.

Below is an Example of File which stores variable in context.xml and is available for the whole application.The context.xml file contains the default Context element used for all web applications in the system.

context.xml

  <Context>      
     <Parameter name="companyName" value="My Company, Incorporated"/>
  </Context>

The same thing can be defined in the web.xml file as below
web.xml

  <context-param>
     <param-name>companyName</param-name>
     <param-value>My Company, Incorporated</param-value>
   </context-param>

To access the context variable in Servlet you can use the following code in doGet() Method as below
Test.java

 
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
  ServletContext servletContext = getServletContext();		  
  PrintWriter out = response.getWriter();
  out.print(servletContext.getInitParameter("companyName"));  
}

Case1: The context variable in web.xml will have highest priority than context.xml in server and application if override attribute is set to true or if it is undefined.

Case2: Defining a context variable in $CATALINA_BASE/conf/context.xml and context.xml file inside your application the former will have more privilege.

Declaring context attributes in web.xml is better since they will work when you deploy your app in other App Servers other than Tomcat.

What is Context Path
A web applications context path is the directory that contains the web applications WEB-INF directory.It points to WebContent directory in your project.

Server context path is the one which tells the location where the WebContent directory is placed during project deployment in server.The following code tells you how to find server context path.

Test.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
{	
   ServletContext servletContext = getServletContext();		
   String contextPath = servletContext.getRealPath(File.separator);
   PrintWriter out = response.getWriter();
   out.println("<br/>Context path: " + contextPath);
}  

The above code outputs some directory within tomcat folder like one below
Output

Context path:  D:\Tomcat\wtpwebapps\CustomTag\ 

In my case D:\Tomcat\ is where my tomcat is installed and wtpwebapps\ is the context where my project
\CustomTag\ is deployed

Leave a reply