Java Reference
In-Depth Information
The application Object
The application object holds a reference to the javax.servlet.ServletContext retrieved
from the servlet configuration. The following code snippet, from the JSP's generated servlet,
shows how the application object is initialized:
pageContext = _jspxFactory.getPageContext(this, request, response,
“errorpage.jsp”, true, 8192, true);
application = pageContext.getServletContext();
You can see that the generated servlet simply gets a reference to the current ServletContext
and stores it in the application object. The application object has application scope, which
means that it is available to all JSPs until the JSP engine is shut down.
The application object is most often used to access environment information. Some of the
more common pieces of information accessed by the application object are objects that are
stored in the ServletContext . These objects are stored there so that they will be available the
whole time the servlet engine is running.
The ServletContext is a great place to share objects between JSPs and servlets. In the follow-
ing example, you use the application object to store and access our application's specific
information. You will do this by creating a JSP that creates a Properties object with the fol-
lowing properties:
PROP1:VAL1
PROP2:VAL2
PROP3:VAL3
You can see that your property object contains three name:value pairs. Next, you will create a
JSP that checks the application for a reference to the Properties object, by calling the
application.getAttribute() method with a key that represents the object in the
ServletContext . If you do not find the referenced object, you will create it and store the
object in the ServletContext using the application.setAttribute() method. Now the
Properties object is available to other JSPs and servlets. Listing 15.3 contains this JSP.
L ISTING 15.3
StoreInApplication.jsp
<%@ page errorPage=”errorpage.jsp” %>
<%@ page import=”java.util.Properties, java.util.Enumeration” %>
<html>
<head>
<title>UseApplication</title>
</head>
<body>
Search WWH ::




Custom Search