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:

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 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();


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

web.xml file:

     <servlet-class>javabeat. ServletExample</servlet-class>

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

 </ 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

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!