ServletContext Interface
An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application. If any information is shared to many servlet, it is better to provide it from the web.xml file using the <context-param> element.
Usage of ServletContext Interface
- The object of ServletContext provides an interface between the container and servlet.
- The ServletContext object can be used to get configuration information from the web.xml file.
- The ServletContext object can be used to set, get or remove attribute from the web.xml file.
- The ServletContext object can be used to provide inter-application communication.
Methods of ServletContext Interface
Method |
Description |
public String getInitParameter(String name) |
Returns the parameter value for the specified parameter name |
public Enumeration getInitParameterNames() |
Returns the names of the context's initialization parameters |
public void setAttribute(String name,Object object) |
sets the given object in the application scope |
public Object getAttribute(String name) |
Returns the attribute for the specified name |
public Enumeration getInitParameterNames() |
Returns the names of the context's initialization parameters as an Enumeration of String objects |
public void removeAttribute(String name) |
Removes the attribute with the given name from the servlet context |
Example Code
DemoServ.java |
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServ extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
//creating ServletContext object
ServletContext context=getServletContext();
//Getting the value of the initialization parameter and printing it
String driverName=context.getInitParameter("dname");
pw.println("driver name is="+driverName);
pw.close();
}}
|
index.html |
<a href="context">Click here</a> |
web.xml |
<?xml version="1.0"?>
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DemoServ</servlet-class>
</servlet>
<context-param>
<param-name>dname</param-name>
<param-value>JdbcOdbcDriver</param-value>
</context-param>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>
|
Output
For more RTU V Sem Advance Java Lab Experiments Click here