ServletContext

tutorial and example
tutorial and example

ServletContext interface is used to provide the configuration information per web application explicitly. Thus unlike ServletConfig, ServletContext interface can be used to provide information to more than one servlet of web application from web.xml file.

So if we want to pass the same information to all servlets of a web application then passing it from web.xml file at once is much efficient way than providing the same information in each servlet separately.

For sharing information from web.xml we need to pass the name in <param-name> and value in <param-value> tags. <context-param> contains these tags.

Methods  of ServletContext interface

              Methods

           Description

Object getAttribute(String name)

This method returns the attribute of specific name.

Enumeration getAttribute()

This method returns the enumeration of attributes names.

String getInitParameter(String name)

This method returns the parameter of name in the form of string.

String getServletInfo()

This method returns the information about servlet container such as its name and version.

void removeAttribute(String name)

We can remove the attributes of name using this method.

Example of ServletContext interface

In this example, two java servlet classes are taken. Both classes contains different information of students of same college. So instead of providing college name every time we are sharing this information from web.xml file.

DemoServletContext.java

DemoServletContext1.java

Web.xml

Output: