JSP and Beyond

a pragmatic primer on building web-based solutions with Java technologies

Implicit Objects

Within each JSP page there are a series of objects that can be used to access and set information all with some type of scope.  The following table provides a practical overview of each.  It is not necessary to know every single one of these off of the top of your head, but common objects, such as the request and session objects, will become a big part of your life when developing JSP pages.

Cookies, querystring variables and other pieces of data are readily accessible from the request object.

For instance, by using the following expression <%= request.getParameter(”ProductID”) %> , the “ProductID” argument from the querystring can be captured and displayed.  This is very useful for easily passing ID information between pages of an application.

Response is used to send information to the client.  A good example might be setting a cookie.  The following block of code sends a cookie to the client that can be retrieved at a later time through the request object <% response.addCookie(myCookie) %>.

Allows you to access configuration settings in the web.xml deployment descriptor for your application.  This is very useful when trying to access name value pairs that may adjust based on where your application is deployed.

When using a scriptlet, it is possible to send output to your HTML page within the scriptlet code by using the out object. The following sample of code uses out object’s print method to send text to the HTML page <% out.print(”some text here”) %>

The session object is useful for storing small amounts of information that will be accessible throughout a users visit to your application or web site.  A good example might be their user ID so you will not have to continually query a database to find this information.

Similar to the session object, the application object allows you to store generally small amounts of data across many page requests.  Unlike the session object the application object values will be available to all user sessions.

The page object represents the current request.  There is generally no practical use for the page object when developing JSPs.

In order to leverage the implicit exception object the page directive attribute must be set to true.

The pageContext object provides access to all of the above objects.  As an example, we can see that the following code mySession = pageContext.getSession() will return the session object for the current user.  In your JSP you could also access the session object directly without using the pageContext object.

Practically, the pageContext object can be used to get and set attributes such as <% pageContext.getAttribute(“MyShoppingCart”) %> to store or retrieve data.