Difference ServletContext and PageContext

Difference ServletContext and PageContext

ServletContext and PageContext are both context objects used in JavaServer Pages (JSP) and servlets, but they serve different purposes and have different scopes.

ServletContext

ServletContext  is an interface that provides a way to communicate with the servlet container. It is an application-wide context that allows servlets to share information. It is used to:

  • Access application-level parameters configured in the deployment descriptor (web.xml).
  • Share data among all the servlets and JSPs within an application.
  • Access resources (like files) available in the web application.

 ServletContext and PageContext

Example
Example:
java
// In a servlet
ServletContext context = getServletContext();
String appName = context.getInitParameter("applicationName");
context.setAttribute("sharedData", "This is shared data");

PageContext

PageContext is an abstract class that provides context information for a JSP page. It is a page-level context that gives access to various objects (like request, response, session) and attributes within the current page. It is used to:

  • Access request, response, session, and application objects.
  • Store and retrieve attributes at the page scope.
  • Access page-level attributes and handle error information.

Difference ServletContext and PageContext

Example
jsp
<%
    PageContext pageContext = pageContext;
    pageContext.setAttribute("pageData", "This is page-specific data");
%>

Major Differences

1. Scope

  •  ServletContext : Application-wide scope. It is available to all servlets and JSPs within the application.
  •   PageContext : Page-level scope. It is available only within the JSP page.

2. Usage

  1.  ServletContext : Used to share data among all components of the web application and to access application-wide parameters and resources.
  2.  PageContext : Used to manage attributes and objects within a specific JSP page.

3. Accessibility

  • ServletContext : Accessible from any servlet or JSP within the application.
  • PageContext : Accessible only within the specific JSP page it is associated with.

Homepage

Readmore