Question : Examples of ServletContext Interface
Ans : 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.
Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to
make it available for all the servlet. We provide this information from the
web.xml file, so if the information is changed, we don't need to modify the
servlet. Thus it removes maintenance problem.
Usage of ServletContext Interface
There can be a lot of usage of ServletContext
object. Some of them are as follows:
1. The
object of ServletContext provides an interface between the container and
servlet.
2. The
ServletContext object can be used to get configuration information from the
web.xml file.
3. The
ServletContext object can be used to set, get or remove attribute from the
web.xml file.
4. The
ServletContext object can be used to provide inter-application communication.
Commonly used methods of ServletContext
interface
There is
given some commonly used methods of ServletContext interface.
1.
public String
getInitParameter(String name):Returns the parameter value
for the specified parameter name.
2.
public Enumeration
getInitParameterNames():Returns the names of the context's
initialization parameters.
3.
public void
setAttribute(String name,Object object):sets the given object in
the application scope.
4.
public Object
getAttribute(String name):Returns the attribute for the specified name.
5.
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.
How to get the object of ServletContext
interface
1. getServletContext() method of
ServletConfig interface returns the object of ServletContext.
2. getServletContext() method of
GenericServlet class returns the object of ServletContext.
Syntax of getServletContext() method
1. public ServletContext getServletContext()
Example of getServletContext() method
1. //We can get the ServletContext object from ServletConfig object
2. ServletContext application=getServletConfig().getServletContext();
3.
4. //Another convenient way to get the ServletContext object
5. ServletContext application=getServletContext();
If this information is important to you , and you want to , I will continue writing some more details of programming language, so click on the advertising, available on this page. This is motivate me for writing some more blogs.
Comments
Post a Comment