JSP Predefined Variables - JSP

In this part of the chapter you will find the predefined variables that are implicitly available for you to use within your JSP.These variables are compared with those that are available in ASP, if you are familiar with that particular technology.

The Roles of the JSP Predefined Variables

There are nine predefined variables made available to you by the Web container. Such variables are known as implicit objects, due to the fact that you can use the variables by name within the Java code on a JSP, without ever having declared them yourself.To see exactly why this is the case, you will be shown the source code that is generated for the servlet that serves the JSP.

The nine implicit objects are application, config, exception, out, page, pageContext, request, response, and session. Some of these are defined in the servlet API (application, config, request, response, and session); the others are defined in the JavaServer Pages API (exception, out, page, pageContext). At the start of a _jspService method, you will see code similar to that shown in

Listing All but the exception object are defined at this point, either as parameters to the _jspService method, or as local variables inside it.The exception object is only available in error pages. An error page is a JSP that uses the page directive with its isErrorPage attribute set to true.

Note that because the implicit objects are either parameters or local variables of the _jspService method, they are only available from within that method.The implication of this when writing a JavaServer Page is that the implicit objects are not available in declaration tags. Remember that declaration tags are used to declare variables and methods that belong to the generated servlet.

Listing 2.18 A _jspService Method

The application Object

This object implements the javax.servlet.ServletContext interface.This interface provides methods that enable a servlet to query for information about its environment as well as write messages and errors to log files. For example, a servlet can query for the major and minor version numbers of the servlet API that is supported by the Web container.The javax. servlet. ServletContext interface is implemented by a service inside the Web container, and accessed by the servlet when necessary.When writing a servlet, you can obtain a reference to the ServletContext via the ServletConfig object that is passed to the servlet when it is initialized.You call the getServletContext method of the ServletConfig object to retrieve the ServletContext.The code in Listing 2.18 retrieves the ServletContext and ServletConfig objects via the pageContext object, discussed later.

A very useful feature of the application object is that it enables you to store objects by name.These stored objects are accessible by any JSP that is running as part of the application, and are therefore useful to share data between the pages.

The example pages in Listing and Listing illustrate how one page can create an object that is visible to any other page that is in the same application.

The second and third lines of Listing create a String object that contains a message, and line 11 then creates a hyperlink to another page that retrieves the shared object and displays it.The JSP in Listing looks like the screenshot in Figure when viewed.

Listing 2.19 Page Creating a Shared Object

Listing 2.20 Page Retrieving a Shared Object

Page Retrieving a Shared Object

The shared object created by the first page is retrieved by the third line of Listing . The following line 12, then, embeds the retrieved value into the current page:

The output from the JSP in Listing is shown in Figure.

output from the JSP in Listing

The code that is generated when you use the application object is shown in Listing for the first page . Unsurprisingly, the code from the scriptlet in Listing is simply pasted into the _jspService method immediately after the implicit object is set up .

Listing 2.21 _jspService When Using application Object

Similarly, for the JSP in , the scriptlet that retrieves the shared object is inserted into the _jspService method as is. In , the second line retrieves the shared object, and the following line embeds its String value into the page:

out.print( theSharedObject );

Listing 2.22 _jspService When Retrieving a Shared Object

The config Object

This variable is the ServletConfig object for the current page:

Thus, the config object provides methods that allow access to any initialization information provided to a servlet.

The exception Object

When writing application software, it is of the utmost importance to consider not just what you expect the user to do, but also what you do not expect! Users do not always follow the “rules” you have laid down for using the application.

So a Web application does not simply crash, it is important to write code that deals with unexpected situations during execution.The application programmer needs to decide at design-time what error-handling logic to put into place.There are several ways that you can deal with such circumstances when writing the application code. For example, the C programming language provides a global variable to track errors.

An alternative would be to check a return value from functions, as in the COM programming style, to determine if a function has executed correctly. The downside of using either of the two techniques just mentioned is that there is no way to force the application programmer to use them! The Java programming language provides an exception-handling mechanism that is compiler-enforced (except for exceptions that are subclasses of java.lang.RuntimeException, of course).

This mechanism is extensible in that you can write your own exception classes that are usually subclasses of java.lang.Exception.You can then instantiate these objects when necessary, and throw them to indicate that an error has occurred in your application code.The question is then,“What happens next?”

From a JSP viewpoint, the standard Java exception mechanism rules are followed. If you do not provide a try/catch block on the page, the exception propagates up the call stack looking for an appropriate handler.This of course raises another question, “What if a handler is not found?”These questions are answered later with the aid of examples.

The way in which you can provide error handling in JSP is by writing error pages.You saw the page directive in Table that can have attributes including errorPage and isErrorPage. An error page is simply a Web page that informs users that errors have occurred in a Web application. During the development process, it is common for many pages to propagate errors to a single error-handling page that can prettify the exception and display it in a way that is helpful during the debugging process.

When the Web application is deployed, it is also common to have multiple pages that use a common error page.This means that the error page should be sophisticated enough to deal with errors from multiple sources, and that the multiple sources are related in such a way that having a common error page is a logical choice The JavaServer Page in Listing uses the page directive on the first line to specify that any exception that occurs during the processing of the page should be passed to the processError.jsp page located in the same directory (because the file is specified with a relative URL).

Listing 2.23 A Page That Generates Exceptions (generateError.jsp)

Thus, the first time that this page is viewed, you see the message in Figure .When you click the Generate Exception! button though, the form submits a value for the hidden field back to the same page.When this value is submitted, the scriptlet throws a java.lang.NullPointerException.Any exception could be thrown at this point, including one that you write.A NullPointerException was chosen for this example simply to show the syntax without cluttering the example with extra code

Page generates an exception

As soon as the exception is thrown, it is passed to the processError.jsp page, as specified using the page directive.The reason for this becomes obvious when you examine the source code for the generated servlet .The page directive causes the error page to be set, and the scriptlet is as follows:

Thus, when the last line of the scriptlet throws the NullPointerException, it is caught by the try/catch block inside the _jspService method

catch (Throwable t) {

and handled by the pageContext object that is responsible for forwarding the exception to the processError.jsp page.

Listing 2.24 Generated Servlet for Listing 2.19

The page that receives the errors is shown in Listing .The first line uses the page directive to indicate that this is an error-handling page and, therefore, the implicit exception object should be made available.The error-handling logic itself is as follows:

A screenshot is not shown here because the output is trivial in this case; the same is true for the generated servlet.There is, however, something new at the beginning of the generated _jspService method:

Throwable exception = (Throwable) request.getAttribute(“javax.servlet.jsp.jspException”);

This line of code is a result of the isErrorPage attribute having a value of true (first line of Listing 2.25). Bear in mind that it is possible to view the processError.jsp page directly, which is why it is important to perform a check in the code to ensure that the exception object is available before trying to invoke any methods on it.

Listing 2.25 Error-Handling Page (processError.jsp)

Finally, if a JSP that did not specify an error page threw an exception, the Web container would generate some kind of error page similar to Figure .The code that generated this page is the same as Listing with the omission of the page directive, and the logic of the if statement inverted to give

Notice that in this example the body of the HTML page is not processed because the scriptlet throws a NullPointerException immediately.

Error-Handling Page (processError.jsp)

The out Object

You can send output back to the client by using the out object.You will notice from Listing that the out variable is of type JspWriter.This class is a subclass of java.io.Writer, and provides a set of print methods that enable you to display primitives and String objects.The class inherits a set of write methods from its parent class, and in many of the examples in this chapter you see that the generated servlet uses both print and write methods.The print method tends to be used for anything that you embed into the page, whereas the write method is used to output the static text parts of the JSP. However, if you look at the source code for the JspWriterImpl class that ships with Tomcat, you can see that the print methods are implemented by delegating to the write methods.You can set the size of the output buffer of a JspWriter by using the page directive and its associated buffer attribute

The out object is only really used in practice from within scriptlets. For example, you do not need to use the out object when using expression tags, where you specify an expression that can be converted to a Java String object. If you refer to Listing, you see an example:

<%= (int) (Math.random() * 10) %>

Note that the expression to be embedded in the page does not terminate with a semicolon character (;).The generated code is shown in Listing , which does in fact call the out.print() method for you.

There have been several examples in this chapter that use the out object to display data, either directly or within the generated servlet code, so another example is not included at this point.

The page Object

This variable corresponds directly to the this reference in the generated servlet.The page object is not typically used when writing a JavaServer Page.The type of situation where it might be useful is when there is a script on the page that needs to call methods that take a parameter that is a reference to the page itself.

The reason for the existence of the page object is that in the future there might be programming languages other than Java that can be used as the scripting language for a JavaServer Page (see the page directive’s language attribute in Table .

The pageContext Object

Although each JSP container has its own implementation for the implicit objects and page attributes, there is a uniform way to access them.The JSP container generates code inside the _jspService method to instantiate the pageContext object, that provides methods that enable you to retrieve references to the other implicit objects (see Table ). It also enables you to store and retrieve objects via an attribute mechanism that uses a name/value pair. Forwarding and redirection of requests is also supported, and is how error handling is internally implemented.You saw this in Listing

pageContext.handlePageException(t);

The pageContext object is an instance of a class that subclasses the abstract

javax.servlet.jsp.PageContext class.

Table Convenience Methods of the javax.servlet.jsp.PageContext Class

Table Convenience Methods of the javax.servlet.jsp.PageContext Class

The request Object

When a user makes a request of a JSP (or servlet), that request is usually modeled by an object that implements the javax.servlet.http.HttpServletRequest interface. The object is passed as a parameter to the _jspService method.The HttpServletRequest interface inherits from the javax.servlet.ServletRequest interface, and provides methods to

  • Read the HTTP headers
  • Acquire information about the request’s content
  • Identify client and server machines, plus the protocol used
  • Crack open the querying URL into its constituent parts
  • Access parameters and attributes
  • Manage user security
  • Access user session information

Requests with parameters can be made in a variety of ways. For example, you can have a hyperlink in an HTML page such as <A HREF=”displayDetails.jsp?name=Mark&age=30”>Send details</A>

In this case, the details.jsp page receives two named parameters.The parameter name has the value Mark, and a parameter called age with a value of 30.To make the request take dynamic values, you can use HTML forms with named input fields. In JSP, you can avoid passing parameters as strings on the query string by using a JavaBean that stores all the data.

The response Object

The javax.servlet.ServletResponse interface defines methods that enable a servlet to send a response back to the client.The _jspService method receives a parameter of type javax.servlet.jsp.HttpServletResponse, which inherits from ServletResponse.You can use the response object to

  • Set content type (MIME type) and length
  • Write binary and textual data
  • Encode URLs with a session ID for robust session tracking
  • Set HTTP headers
  • Manage user session information

The session object

The HTTP protocol is known as a stateless protocol because client requests are each opened over a separate connection, and the server does not maintain any contextual information that could form the basis of a conversation between the client and the server. Several solutions are commonly used today that get around this problem, two of which are cookies and URL rewriting.

Cookies are small files sent by a server to a client, which contain user identification information. Upon subsequent requests, a server can request the cookie from the client, and thus maintain server-side state on behalf of the client (such as the contents of a shopping cart).

Many users disable cookies, and a fallback mechanism that the server can use in such situations is URL rewriting. In this case, the client appends extra information to the end of the URL that it requests of the server.This extra information identifies the client to the server. However, writing the code that deals with cookies or URL rewriting is tedious and error-prone.The Servlet API provides a high-level solution that is generally implemented using cookies or URL rewriting.

JSP Variables and ASP Variables

For those of you who are familiar with Microsoft’s Active Server Pages (ASP) technology,this brief section mentions some of the similarities that exist between ASP and JSP. For example, they both use object-oriented, server-side scripting. ASP supports two main scripting languages:VBScript and JScript. ASP also has a set of intrinsic objects that are available for the scripts to utilize.

The ASP intrinsic objects that correlate to JSP implicit objects are listed in Table. You can see that there is a direct relationship between most of the variables.The only exception is that ASP provides the Response.Write method to provide access to the output stream, whereas JSP has the out object.

Table Implicit Objects in ASP and JSP

Table Implicit Objects in ASP and JSP

Both JSP and ASP use the same syntax for directives (<%@ … %>), expressions (<%= …%>), and scripting (<% … %>).The code in Listings shows a simple example of ASP and JSP, and from them you can see how similar the two approaches are.

Listing 2.26 ASP Example

Listing 2.27 JSP Example


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

JSP Topics