Servlet Context

Servlet Context is used to communicate with the servlet container to get the details of web application. It is created at the time of deploying the project. There is only one Servlet Context for entire web application. Servlet Context parameter uses <context-param> tag in web.xml file.

Methods of ServletContext interface:

NameDescription
String getInitParameter(String)It returns the Servlet initialization parameter of the given name and if the requested parameter is not available then it returns null.
Enumeration getInitParameterNames()It returns names of all Servlet initialization parameters defined in web.xml file.
void setAttribute(String, Object)Sets an attribute with the current request.
Object getAttribute(string)Returns the value of an attribute located with the given name or returns null value if an attribute with the given name is not found.
Enumeration getAttributeNames()Returns all the attribute names in the current request.
void removeAttribute(String)Removes an attribute identified by the given name from the request.
getRequestDispatcher( )This method takes a string argument describing the path to located the resource to which the request is to be dispatched..

Servlet Context Example

Following example shows use of ServletContext:

package  javabeat;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletExample extends HttpServlet
{
public void doGet(HttpServletRequest request,  HttpServletResponse   response)
	throws IOException
  {

	PrintWriter pw = response.getWriter();
	pw.println(getServletContext().getInitParameter(&amp;quot;Welcome&amp;quot;));

   }
}

Here getInitParameter() is used to initialize the parameter from the web.xml file.

web.xml file:

  <web-app>
  <servlet>
     <servlet-name>ServletExample</servlet-name>
     <servlet-class>javabeat. ServletExample</servlet-class>
   </servlet>

   <context-param>
<param-name>Welcome</param-name>
<param-value>Welcome to javabeat!!!!!!!!!</param-value>
   </context-param>

   <servlet-mapping>
       <servlet-name>ServletExample</servlet-name>
       <url-pattern>/ServletExample</url-pattern>
   </servlet-mapping>
 </ web-app>

Here <context-param > tag contains two tags namely <param-name> and <param-value> which is used to initialize the attributes of the servlet.

The output of the following program is:
Servlet Context output

Previous Tutorial : Web.xml  || Next Tutorial :  Request Dispatcher

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Could you give one example when to use servlet cotext & config parameter, please provide one relevent examples.

Speak Your Mind

*