JSP implicit objects are
objects that can be used in a JSP without having to be declared or
initialized. They are actually declared and initialized behind the
scenes by the application server when the JSP is deployed.
In the previous section's example, we used the JSP implicit object out. This object, for all practical purposes, is equivalent to calling the HttpResponse.getWriter() method in a servlet. In addition to the out
object, there are several other implicit objects that can be used in
JSP scriptlets. These implicit objects are listed in the following
table:
Implicit object
|
Implicit object class
|
Description
|
---|
application
|
javax.servlet.ServletContext
|
Equivalent to calling the getServletContext() method in a servlet.
|
config
|
javax.servlet.ServletConfig
|
Equivalent to invoking the getServletConfig() method in a servlet.
|
exception
|
java.lang.Throwable
|
Only accessible if the page directive's isErrorPage attribute is set to true. Provides access to the exception that was thrown, that led to the page being invoked.
|
out
|
javax.servlet.jsp.JspWriter
|
Equivalent to the return value of HttpServletResponse.getWriter().
|
page
|
java.lang.Object
|
Provides access to the page's generated servlet.
|
pageContext
|
javax.servlet.jsp.PageContext
|
Provides several methods for managing the various web application scopes
(request, session, application). Refer to the JavaDoc for PageContext at http://java.sun.com/javaee/5/docs/api/javax/servlet/jsp/PageContext.html.
|
request
|
javax.servlet.ServletRequest
|
Equivalent to the instance of HttpServletRequest we obtain as a parameter of the doGet() and doPost() methods in a servlet.
|
response
|
javax.servlet.ServletResponse
|
Equivalent to the instance of HttpServletResponse we obtain as a parameter of the doGet() and doPost() methods in a servlet.
|
session
|
javax.servlet.http.HttpSession
|
Equivalent to the return value of the HttpServletRequest.getSession() method.
|
The following example JSP illustrates the use of several of the JSP implicit objects:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.util.Enumeration"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Implicit Objects Demo</title>
</head>
<body>
<p>This page uses JSP Implicit objects to attach objects to the request, session, and application scopes.<br />
It also retrieves some initialization parameters sent in the web.xml configuration file.<br />
The third thing it does is get the buffer size from the implicit response object.<br />
</p>
<p>
<%
application.setAttribute("applicationAttribute", new String( "This string is accessible across sessions."));
session.setAttribute("sessionAttribute", new String( "This string is accessible across requests"));
request.setAttribute("requestAttribute", new String( "This string is accessible in a single request"));
Enumeration initParameterNames = config.getInitParameterNames();
out.print("Initialization parameters obtained ");
out.print("from the implicit <br/>");
out.println("config object:<br/><br/>");
while (initParameterNames.hasMoreElements())
{
String parameterName = (String) initParameterNames.nextElement();
out.print(parameterName + " = ");
out.print(config.getInitParameter((String) parameterName));
out.print("<br/>");
}
out.println("<br/>");
out.println("Implicit object <b>page</b> is of type " + page.getClass().getName() + "<br/><br/>");
out.println("Buffer size is: " + response.getBufferSize() + " bytes");
%>
</p>
<p>
<a href="implicitobjects2.jsp">
Click here to continue.
</a>
</p>
</body>
</html>
This JSP utilizes most of the implicit objects available to JSP scriptlets. The first thing it does is attach objects to the application, session, and request implicit objects. It then gets all initialization parameters from the implicit config object and displays their names and values on the browser by using the implicit out object. Next, it displays the fully qualified name of the implicit page object. Finally, it displays the buffer size by accessing the implicit response object.
JSP (and optionally servlet) initialization parameters are declared in the application's web.xml file. For this application, the web.xml file looks as follows:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>ImplicitObjectsJsp</servlet-name>
<jsp-file>/implicitobjects.jsp</jsp-file>
<init-param>
<param-name>webxmlparam</param-name>
<param-value>
This is set in the web.xml file
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ImplicitObjectsJsp</servlet-name>
<url-pattern>/implicitobjects.jsp</url-pattern>
</servlet-mapping>
</web-app>
Remember that a JSP gets
compiled into a servlet at runtime the first time it is accessed after
deployment. As such, we can treat it as a servlet in the web.xml
file. In order to be able to pass initialization parameters to a JSP,
we must treat it like a servlet, as initialization parameters are placed
between the<init-param> and</init-param> XML tags. As shown in the previous web.xml file, the parameter name is placed between the<param-name> and</param-name> tags, and the parameter value is placed between the<param-value> and</param-value>
tags. A servlet (and a JSP) can have multiple initialization
parameters. Each initialization parameter must be declared inside a
separate<init-param> tag.
Notice that in the previous web.xml
file, we declared a servlet mapping for our JSP. This was necessary to
allow GlassFish's web container to pass initialization parameters to the
JSP. As we didn't want the URL of the JSP to change, we used the JSP's
actual URL as the value for the<url-pattern> tag. If we wanted to access the JSP via a different URL (not necessarily one ending in .jsp), we could have placed the desired URL inside the<url-pattern> tag.
At the bottom of implicitobjects.jsp, there is a hyperlink to a second JSP, called implicitobjects2.jsp. The markup and code for implicitobjects2.jsp looks as follows:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.util.Enumeration"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sanity Check</title>
</head>
<body>
<p>This page makes sure we can retrieve the application, session and request attributes set in the previous page. <br />
</p>
<p>applicationAttribute value is:
<%=application.getAttribute("applicationAttribute")%>
<br />
sessionAttribute value is:
<%=session.getAttribute("sessionAttribute")%>
<br />
requestAttribute value is:
<%=request.getAttribute("requestAttribute")%>
<br />
</p>
<p>
The following attributes were found at the application scope: <br/><br/>
<%
Enumeration applicationAttributeNames = pageContext .getAttributeNamesInScope(pageContext.APPLICATION_SCOPE);
while (applicationAttributeNames.hasMoreElements())
{
out.println(applicationAttributeNames.nextElement() + "<br/>");
}
%>
</p>
<p><a href="buggy.jsp">This hyperlink points to a JSP that will throw an exception.</a></p>
</body>
</html>
In this second JSP, we
retrieve the objects that were attached to the application, session, and
request objects. The attached objects are obtained by calling the
appropriate implicit object's getAttribute() method. Notice how all calls to the getAttribute() method are nested between the<%= and %> delimiters. Snippets of code between these delimiters are called JSP expressions. JSP expressions are evaluated and their return value is displayed in the browser without having to call the out.print() method.
This JSP also retrieves the names of all objects attached to the application scope and displays them in the browser window.
At the bottom of the previous JSP, there is a hyperlink to a third JSP. This third JSP is called buggy.jsp. Its only purpose is to demonstrate the errorPage attribute of the page directive, the error attribute of the page directive, and the exception implicit object. Therefore, it is not terribly complicated.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="error.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Buggy JSP</title>
</head>
<body>
<p>
This text will never be seen in the browser since the exception will be thrown before the page renders.
<%
Object o = null;
out.println(o.toString()); //NullPointerException thrown here.
%>
</p>
</body>
</html>
The only thing this JSP does is force a NullPointerException, which will result in GlassFish's servlet container directing the user to the page declared as an error page in the errorPage attribute of the page directive. This page is error.jsp; its markup and code is shown next:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.io.StringWriter"%>
<%@page import="java.io.PrintWriter"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>There was an error in the application</title>
</head>
<body>
<h2>Exception caught</h2>
<p>Stack trace for the exception is:<br />
<%
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
exception.printStackTrace(printWriter);
out.write(stringWriter.toString());
%>
</p>
</body>
</html>
Notice how this page declares itself to be an error page by setting the isErrorPage attribute of the page directive to true. As this page is an error page, it has access to the exception implicit object. This page simply calls the printStackTrace() method of the exception implicit object and sends its output to the browser via the out implicit object. In a real application, a user-friendly error message would probably be displayed.
As the previous application
consists only of three JSPs, packaging it for deployment simply consists
of putting all the JSPs in the root of the WAR file and the web.xml file in its usual location (the WEB-INF subdirectory in the WAR file).
After deploying and pointing the browser to http://localhost:8080/jspimplicitobjects/implicitobjects.jsp, we should see implicitobjects.jsp rendered in the browser:
As we can see, the JSP has a number of "mysterious" initialization parameters in addition to the one we set in the application's web.xml file. These additional initialization parameters are set automatically by GlassFish's web container.
Clicking on the hyperlink at the bottom of the page takes us to implicitobjects2.jsp:
Notice how the value for the request attribute shows up as null.
The reason for this is that when we clicked on the hyperlink on the
previous page, a new HTTP request was created, therefore any attributes
attached to the previous request were lost. If we had forwarded the
request to this JSP, we would have seen the expected value on the
browser window.
Notice how in addition to
the attribute we attached to the application, GlassFish also attaches a
number of other attributes to this implicit object.
Finally, clicking on the
hyperlink at the bottom of the page takes us to the buggy JSP, which
does not render. Instead, control is transferred to error.jsp:
Nothing surprising is displayed here; we see the exception's stack trace as expected.