ServletContext Interface
Introduction
The object of ServletContext is automatically created by the container when the web application is deployed. There is only one
ServletContext object per web application. It is available on
javax.servlet.* package.
Uses of ServletContext Interface
- It helps to establish communication between container and servlets.
- The ServletContext object also provides inter-application communication.
- ServletContext has init parameter that can be used to get configuration information from web.xml.
- It provides the accessibility of application level parameter.
ServletContext Interface Methods
Following are the important methods of ServletContext interface:
Methods | Description |
---|
Object getAttribute(String name) | Returns the container attribute for specified name. |
void setAttribute(String name, Object obj) | Sets the given ServletContext object in the application scope. |
void removeAttribute(String name) | It removes the attribute with specified name from ServletContext. |
String getContextPath( ) | Returns the context path of the web application. |
String getInitParameterName(String name) | Returns a String value of initialize context parameter. |
String getRealPath(String path) | Returns the real path corresponding to given virtual path. |
int getMajorVersion( ) | Returns the major version of the Servlet API that the servlet container supports. |
Getting Object of ServletContext Interface
- The ServletConfig interface provides a getServletContext( ) method to return the object of ServletContext.
- The GenericServlet class also provides the getServletContext( ) method to return the object of ServletContext.
Example
ServletContext app = getServletConfig( ).getServletContext( );
Or
ServletContext app = getServletContext( );