Download Further JSP Syntax and more Slides Java Programming in PDF only on Docsity!
Further JSP Syntax
I N THE PREVIOUS CHAPTER, YOU WERE EXPOSED to the core of the JSP syntax.The
chapter showed you how to embed Java code into your pages, it showed you the prede-
fined variables, and it introduced you to the JavaServer Pages Standard Tag Library
(JSTL).
In this chapter, see the role of what are known as standard actions, and you will be
introduced to custom actions.The chapter will then progress to the Expression Language
where you will discover how it can be used directly within pages, reducing further the
need to have Java code embedded in your pages.
The Standard Actions
Since the earliest versions of JSP, there have been what are referred to as standard actions.
These are special XML-like tags (XML is discussed in the introduction to Chapter 10,
“Utilizing XML from JSP”).They take the form of an XML tag with a namespace-pre-
fixed jsp, so a standard action always looks something like this:
.. .
They are used for the following functions:
n Forwarding requests and performing includes in pages.
n Embedding the appropriate HTML on pages to invoke the Java plugin to be used
within browsers to run Java applets.
n The interaction between pages and JavaBeans.
n The provision of additional functionality to tag libraries.
We’ll look at these functions here, and you will see some being used in other contexts in
later chapters.
88 Chapter 3 Further JSP Syntax
Forwarding and Including
When a request is received by a JSP, it can be forwarded directly onto another relative
URL from the same Web application to be processed.This must be a resource within the
same Web application.To do this, you can use the standard action.
Forwarding is not the same as redirecting. Redirecting involves the browser being sent
elsewhere for a resource, effectively resulting in the browser issuing two requests.
Forwarding is the browser requesting a resource, and the response coming from the
resource that has been forwarded to. Following is a basic page, which uses the
standard action:
anything here will not appear in the browser
anything here will not appear either
Pages that forward requests cannot send any content to the browser. In the very basic
example shown previously, neither of the two fragments of text will appear in the brows-
er because the request and response have been forwarded to gotForwardedRequest.jsp.
Use of the action creates the automatically generated code in the
compiled servlet, as shown in Listing 3.1.
Listing 3.1 Autogenerated Source from JSP Using
// note that some code has been removed for brevity public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { ... try {
... out.write(“anything here will not appear in the browser\r\n”); if (true) { pageContext.forward(“gotForwardedRequest.jsp”); return; } out.write(“\r\nanything here will not appear either”); } catch (Throwable t) { if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (pageContext != null) pageContext.handlePageException(t); ... } }
You can see from Listing 3.1 that the standard action becomes a call to the forward()
method of the javax.servlet.jsp.PageContext object.
90 Chapter 3 Further JSP Syntax
This is now accessible to the resource that the request was forwarded to using a basic
statement like:
String value = request.getParameter(“myParam”);
This ability to pass parameters can be very helpful because the values of these parameters
can be dynamic.
A complete example of this is part of the chapter download as pages
passingParameters.jsp and accessingParameters.jsp.
Templating Pages Using
The third standard action we will discuss is the action. In Chapter 2, the
include directive was introduced, which includes static content into your JSP.
The include directive is not always appropriate, however, because the included con-
tent is included as static text (see Chapter 2).The include standard action, however,
processes any included files at runtime. In other words, when the servlet is invoked by a
client, the included file is dynamically obtained.This results in the ability to include con-
tent that is being changed regularly, and also the ability to include output from other
JSPs that are providing dynamic content.
The include action can be used to include the output from one JSP within another,
and thus, you can build up templates of JavaServer Pages that make up complete Web
pages. In fact, this is how the front ends of many Web sites are built. Figure 3.1 shows a
diagram of what is meant by this.
Figure 3.1 Templating using .
Listing 3.2 shows a JSP that is built in this way with the use of includes.
contents.jsp
header.jsp
index.jsp
footer.jsp
menu.jsp
The Standard Actions 91
Listing 3.2 usingIncludes.jsp
Using Includes
As you can see from Listing 3.2, the action has two attributes.The two
attributes are shown in Table 3.1.
Table 3.1 The Attributes of
Name Description
page This attribute specifies the page to be included. It must contain a relative
URL.
flush The flush attribute specifies what should happen to any buffered content that
appears within the including page up until the include. See the short listing
below:
content here could be buffered
What happens to the text content here could be buffered can be determined by the
value of the flush attribute. If the text is buffered, and the flush attribute is
true, it will be flushed before the include is processed. If the flush attribute is
set to false, any buffered content will not be flushed.
The significance of this is that the buffer needs to be flushed for output to be
sent to the browser, so most of the time, you set to true.There were some
specific situations in JSP 1.1 a value of false was required.
Note that the default is false, so you will need to specify a value of true.
As with the standard action, you can also pass parameters to included
pages using the standard action. A basic example is shown here:
The Standard Actions 93
/WEB-INF/includes/header.jspf /WEB-INF/includes/footer.jspf
Figure 3.2 Output from usingIncludesWithParameters.jsp.
The defines a group of pages, and within it you can set includes
for the top of the pages , and includes for the foot of the pages
.This is ideal when you are using the same headers or footers on every
single page.The element specifies which JSPs are to be included in the
group, in this case, all of them with the .jsp extension.
The Java Plugin
In this section, you will be introduced to three more standard actions:
n (^) n (^) n (^)
You will also see an additional use for the element.
If you are planning to use Java applets within your application, you need to make sure
that the client browsers support the applet you plan to use. One of the most frustrating
aspects of applet development is the fact that you are reliant on the client browser virtual
machine. Although Java is sometimes referred to as a “write once, run anywhere” lan-
guage, in my experience, writing Java applets can be more like “write once, debug every-
where!”This is because the virtual machines in the browsers have various issues depend-
ing on the browser in use, and the platform on which the browser is running. Microsoft
stopped shipping a Java virtual machine with its browser, requiring it to be downloaded
separately; and on XP platforms, even that is no longer permitted. So, the reality is this:
The more widely used browser (Internet Explorer) does not have very straightforward
support for Java applets, and none at all in certain environments.
The traditional way to embed a Java applet into an HTML page is shown in Listing
3.4.This listing will not work in Internet Explorer where a virtual machine is not
installed.
94 Chapter 3 Further JSP Syntax
Listing 3.4 applet.html
Not using the Java Plugin
Applet running in the browser
It is against this backdrop that the Java Plugin comes in.This neat little bit of software is
a plugin to the browser; the same way that Shockwave or Real Audio can be installed as
a plugin to your browser to provide support for complex animations or streamed media.
The Java Plugin basically provides a Java virtual machine that can be used by browsers to
run Java applets in a fully compliant virtual machine from Sun.Various plugins are avail-
able for various versions of the Java programming language.
The Java Plugin can be installed from http://java.sun.com/getjava/.
The fundamental problem with this is that going to this URL is fine for Java-savvy
developers like you and me, but how many regular Internet users are going to want to
“faff about” trying to find this URL simply so they can use your online calculator or
whatever your applet does.
Note
Faffing is a British term often used to denote someone wasting time or not getting straight to the point.
The Java Plugin can be installed automatically if required, and this is achieved using
some specific HTML that needs to go into your page.This is where the
include comes in really useful. Its role is to automatically put in the required HTML
code to enable a browser to run your applet using the Java plugin, and also install it if it
is not already present. Listing 3.5 demonstrates the use of the Java Plugin.
Listing 3.5 plugin.jsp
Using the Java Plugin
Applet running in the plugin
96 Chapter 3 Further JSP Syntax
Your browser can’t display this applet. Sorry
The OBJECT tag is there for Microsoft Internet Explorer, and the EMBED tag is there for
Netscape.When this page is running on a Windows platform, you will get a Java icon in
your system tray.This is shown in Figure 3.3, which shows Internet Explorer showing
this page.
Listing 3.6 Continued
Figure 3.3 plugin.jsp in the browser.
The Standard Actions 97
Using JavaBeans on Pages
Three standard actions are associated with the use of JavaBeans on JavaServer Pages.
JavaBeans are Java classes written to a certain specification which includes that they can
have get and set methods for their properties.They also have a public no argument con-
structor.The standard actions allow the instantiation of beans, and also the setting and
getting of their properties:
n enables the use of JavaBeans within JavaServer Pages. It specifies
the Beans to be used on a specific page.
n is used to access Bean properties from pages.
n is used to set properties from pages.
A basic example is shown here:
The use of JavaBeans on pages is vital if you are going to even begin to separate your
business logic from your presentation.These standard actions associated with JavaBeans
were the first step in the JSP specifications to enable this to be done.The subject of
JavaBeans and their use in JavaServer Pages is discussed in detail in Chapter 6, “JSP and
JavaBeans.”
Actions and Tag Libraries
It is now also possible to create your own custom actions in addition to the standard
actions that have been discussed. Custom actions are discussed in Chapter 9, “Developing
Custom Tag Libraries,” because custom actions are basically custom tags.
When using actions, there are some additional helper standard actions that you have
available to you. One such action is the action.
Consider the following code fragment:
The action enables you to replace any attributes in your tags with
tags, with the attribute value now being element content:
includeFileNeedingAParameter.jsp
You might be wondering what the benefit of this would be. In this specific example
there is no benefit, but, for example, when you have custom actions, you might want
attribute values to contain XML-structured data.This would not be possible if you were
The JSP Expression Language (EL) 99
Listing 3.7 shows a basic JSP that is using the expression language directly in the page.
Listing 3.7 usingEL.jsp
Expression Language Examples <% // set up a page context parameter for use later in the page // normally this would have been set within the context of // an application pageContext.setAttribute(“pageColor”, “yellow”); %>
Welcome to the ${param.department} Department
Here are some basic comparisons:
Is 1 less than 2? ${1<2} Does 5 equal 5? ${5==5} Is 6 greater than 7? ${6 gt 7}
Now for some math: 6 + 7 = ${6+7} 8 x 9 = ${8*9}
You appear to be using the following browser: ${header[“user-agent”]}
The output of Listing 3.7 with the JSP 2.0 early access preview version of Tomcat
appeared as shown in Figure 3.4.
100 Chapter 3 Further JSP Syntax
Figure 3.4 The output from usingEL.jsp in a browser.
Listing 3.7 will be referred to as we progress through the chapter. So, what does the EL
look like? It draws its syntax from two other scripting languages: XPath and
ECMAScript. XPath is used in XML applications and is discussed in Chapter 11,
“Transforming XML Using XSLT and XSLFO.” ECMAScript is mainly used as a client-
side scripting language in Web applications, and is also commonly used in the develop-
ment of Microsoft Active Server Pages.
Note
ECMAScript was developed within the context of the European Computer Manufacturers Association. It is essentially a standardization of Netscape’s JavaScript, which has been widely used as a client-side scripting language in both Internet Explorer (implemented as JScript) and Netscape browsers.
The EL has the following features:
n It has a set of implicit objects available to it.
n It has a comprehensive set of operators.
n It can access collections and nested properties in an intuitive way.
n It has a selection of extensible functions mapping to static methods in Java classes.
102 Chapter 3 Further JSP Syntax
Notice that they all have a text version in addition to the more familiar symbol version.
These are also used in Listing 13.7:
Here are some basic comparisons:
Is 1 less than 2? ${1<2} Does 5 equal 5? ${5==5} Is 6 greater than 7? ${6 gt 7}
The Logical Operators
The logical operators are the same as the Java Programming Language, but they also have
their textual equivalents within the EL.They are shown in Table 3.3.
Table 3.3 The Logical Operators
Symbol Version Text Version
&& and || or
! not
The empty Operator
The empty operator allows you to test the following:
n Object references to see if they are null.
n Strings to see if they are empty.
n Arrays to see if they are empty.
n Lists to see if they are empty.
n Maps to see if they are empty.
You use the operator in the following way:
empty variableName
If any of the above conditions are met, then the operator returns true.
Operator Precedence
The operator precedence works from the highest precedence through to the lowest
precedence, and then left to right - In other words, the same as the Java programming
language. As with any other programming language, you can affect this precedence with
the use of parentheses ().
The operator precedence table as defined by the JSP 2.0 specification is shown below
in Table 3.4:
### The JSP Expression Language (EL) 103
Table 3.4 The Operator Precedence Table for the EL
[].
-(unary) not! empty
- (binary) <> <= >= lt gt le ge == !- eq ne && and || or
Accessing Objects and Collections
In the Java Programming Language, objects and their properties are accessed using get
and set methods.This is because of encapsulation, and it is not considered good practice
to access object properties directly.
So, for example, if there were a hierarchy of objects such as a bookstore, with a book,
and the book had a chapter, the code would be something like
getBookStore().getBook().getChapter(“Ch03FurtherJSP”);
This can look quite messy, and although hiding the variables provides encapsulation, it
is not clear to read, especially within JSPs in code like this:
<%= getBookStore().getBook().getChapter(“Ch03FurtherJSP”) %>
If this were a scripting language such as ECMAScript, it would be something like
bookStore.book.chapters.Ch03FurtherJSP
If you are familiar with ECMAScript, you will have seen how objects can be accessed
in a variety of ways in that language.This is also the case in the EL. So, taking our basic
chapter example one step further, using the EL, you can access this chapter object in the
following ways:
bookStore.book.chapters.Ch03FurtherJSP bookstore[“book”].chapters.Ch03FurtherJSP bookstore[‘book’].chapters[“Ch03FurtherJSP”]
Essentially, what we are saying here is that there are two operators that can be used to
enable you to access objects. One is the dot operator (.), and the other is the [] brack-
ets.When using the brackets, you can place the name of a subproperty as a String in
either double or single quotes within them, as shown. Using the dot enables you to step
down through properties and the various subproperties.
The JSP Expression Language (EL) 105
Now we will use the expression language to access the properties. The person is called ${man.name}, and the password is ${man.password}.
Now a list and a map is created as properties of the GroupPeople class.
<%-- create a GroupPeople object that contains a List and a Map --%>
The map is accessible using the following syntax: The first author is called ${group.mapPeople[“authorA”]}, and the second author is called ${group.mapPeople[“authorB”]}.
The List is accessible also, but using the following syntax: The first author is called ${group.listPeople[0]}, and the second author is called ${group.listPeople[1]}.
In Listing 3.8, you can see the JavaBean related standard actions being used to set up two
beans. One is a Person bean, which is based upon the Java class shown in Listing 3.9,
and the other is a GroupPeople bean, shown in Listing 3.10.
Listing 3.9 Person.java
package com.conygre; public class Person {
private String name; private String password;
public String getName(){ return name; } public void setName(String s){ name = s; } public String getPassword(){ return password; } public void setPassword(String s){ password = s; } }
Listing 3.8 Continued
### 106 Chapter 3 Further JSP Syntax
Listing 3.10 GroupPeople.java
package com.conygre; import java.util.*; public class GroupPeople {
private List listPeople; private Map mapPeople;
public GroupPeople() { listPeople = new Vector(); listPeople.add(“Nick”); listPeople.add(“Mark”); mapPeople=new HashMap(); mapPeople.put(“authorA”, “Nick”); mapPeople.put(“authorB”, “Mark”); }
public List getListPeople(){ return listPeople; }
public void setListPeople(List s){ listPeople = s; }
public Map getMapPeople(){ return mapPeople; }
public void setMapPeople(Map s){ mapPeople = s; } }
The crucial lines within the JSP of Listing 3.8 are the ones that access bean properties
using the EL.They are shown below:
The person is called ${man.name}, and the password is ${man.password}.
... The map is accessible using the following syntax: The first author is called ${group.mapPeople[“authorA”]}, and the second author is called ${group.mapPeople[“authorB”]}.
The List is accessible also, but using the following syntax: