Vous êtes sur la page 1sur 8

http://java.sun.

com/developer/technicalArticles/javaserverpages/JSP20/ Sep 12, 2007

Article
Developing Web Applications With JavaServer Pages 2.0

by Qusay H. Mahmoud
July 2003
JavaServer Pages (JSP) technology, which abstracts servlets to a higher level, is an open, freely-available specification developed by the Java Community Process (JCP) for
generating dynamic content, and a key component of the Java 2 Enterprise Edition (J2EE) specification. Many commercially available application servers (such as BEA
WebLogic, IBM WebSphere, Live JRun, and Orion) support JSP technology.

JSP technology is being used everywhere on the Web including airline reservation systems, banking systems, and shopping. The new release, Version 2.0, is an upgrade to
JSP 1.2 with several interesting new features. The objective of JSP 2.0 is to make the task of developing dynamic Web pages easier than ever without having to learn the
Java programming language.

This article:

• Provides a fast track code intensive tutorial to get started with JSP 2.0

• Describes the new features in JSP 2.0

• Offers a flavor of the effort involved in developing applications using JSP 2.0

• Provides sample code that you can adapt for your own applications
If you are new to JSP, it might be a good idea to start directly with JSP 2.0. However, if you wish to learn about JSP 1.2 you may want to start with this JSP tutorial.

JSP 2.0
JSP 2.0 is an upgrade to JSP 1.2 with several new interesting features that make the lives of Web application designers and developers easier. The objective of JSP 2.0 is to
make JSP easier to use than ever, and more importantly to be used without having to learn the Java programming language itself. It simplifies the Tag APIs by adding a new
extension mechanism called SimpleTag.

In addition to several other improvements, the new key features that have been introduced in JSP 2.0 are:

1. A simple expression language (EL), which can used to easily access data from JSP pages. The expression language simplifies writing scriptless JSP-based
applications without using Java scriptlets or Java expressions.
2. New syntax for defining reusable custom actions using JSP technology directly. The syntax is delivered into .tag and .tagx files which can be written by
developers and page authors.
3. The XML syntax has been improved substantially. The new standard filename extensions (.tagx for tag files and .jspx for JSP files) have been added.

In this article I concentrate on the Expression Language, the simplified Tag API, and tag files. I believe existing JSP developers will find these key features to be very
interesting and useful.

Why the Jump from 1.2 to 2.0?


The version number was originally listed as 1.3 in the Java Specification Request (JSR 152). However, given that the new features would have a deep impact on the
development model of JSP applications as you will see later, the Expert Group felt it was necessary to upgrade the major version number to 2.0 since this would reflect the
impact more appropriately. Also, the new version number will help draw the attention of developers to these new interesting features. The good news is that all valid JSP
1.2 pages are also valid JSP 2.0 pages.

Getting Started with JSP 2.0


In order to get started with JSP 2.0, you need a JSP container that supports the JSP 2.0 specification and the Java Servlet 2.4 specification. Luckily, Jakarta Tomcat 5.0
(Alpha release) supports the new JSP 2.0 and Servlet 2.4 specifications. Download and install Tomcat 5.0.

The JSP Expression Language


Information to be passed to JSP pages is communicated using JSP scoped attributes and request parameters. An expression language (EL), which is designed specifically
for page authors, promotes JSP scoped attributes as the standard way to communicate information from business logic to JSP pages. Note, however, that while the EL is a
key aspect of the JSP, it is not a general purpose programming language. Rather, it is simply a data access language, which makes it possible to easily access (and
manipulate) application data without having to use scriptlets or request-time expression values.

Prior to JSP 2.0, a page author had to use the expression <%= aName %> to access the value of a system, as in the following example:

<someTags:aTag attribute="<%= pageContext.getAttribute("aName") %>">

or the value of a custom JavaBeans component:

<%= aCustomer.getAddress().getCountry() %>

An expression language allows a page author to access an object using a simplified syntax. For example, to access a simple variable, you can use something like:

<someTags:aTag attribute="${aName}">

And to access a nested JavaBeans property, you would use something like:

${aCustomer.address.country}

But, you might ask, isn't this JavaScript syntax? You are absolutely right! If you've worked with JavaScript, you will feel right at home, because the EL borrows the JavaScript
syntax for accessing structured data.

Note: The Expression Language was originally developed as part of the JavaServer Pages Standard Tag Library (JSTL) 1.0, which is a standard tag library that provides
support for common, structural tasks, such as iteration and conditionals, processing XML documents, internationalization, and database access using the Structured Query
Language (SQL). The JSTL specification is being developed by the JSR 52 expert group. For a tutorial on JSTL, please see Faster Development with JSTL.

Accessing Application Data


You can access application data either as a property of an object, using the dot (.) operator, or a named array element using the bracket ['name'] operator.

The expression ${data} represents the scoped variable named data. You can retrieve properties from collections using either the dot (.) or bracket ([]) operator:
• The dot (.) operator is used to retrieve a named property. For example, the expression ${customer.name} indicates the name property of the customer
scoped variable.
• The bracket operator ([]) can be used to retrieve a named property, as in ${customer["name"]}. The bracket operator can also be used as $
{customers[0]} to refer to the first item in the customers collection.
The expression language unifies the treatment of dot (.) and bracket ([]) operators. Therefore, ${customer.name} is equivalent to ${customer["name"]}. As you can
see, all EL expressions must be enclosed between ${ and }.

The EL evaluates an identifier by looking up its value as an attribute using PageContext.findAttribute(String). If the attribute is not found, null is returned.

Operators
The EL supports arithmetic, relational, and logical operators to handle the most common data manipulations. In addition, a special operator for testing if an object is empty is
provided. The operators are shown in Table 1. You can use the empty operator to determine whether a collection or a string is empty or null. For example, ${empty
param.name} will be true only if the request parameter named param is not present. The empty operator can be combined with the ! operator, as in the expression ${!
empty param.name}, which evaluates to true if the request parameter named param is present.

Table 1: Expression language operators

Operator Description

+ Addition

- Subtraction

* Multiplication

/ or div Division

% or mod Modulus (Remainder)

== or = Equality

!= or != Inequality

< or lt Less than

> or gt Greater than

<= or le Less than or equal to

>= or ge Greater than or equal to

&& or and Logical AND

|| or or Logical OR

! or not Boolean complement

empty Check for empty value

a ? b : c Conditional operator

Implicit Objects
In addition to operators, the EL defines implicit objects to support access to application data that is of interest to page authors. The implicit objects defined by the EL are
shown in Table 2. An example of how to use some of these implicit objects is provided later.

Table 2: Implicit objects provided by the expression language

Implicit Object Content

applicationScope A collection of scoped variables from applications scope

cookie A collection of all cookies

header HTTP request headers as strings

headerValues HTTP request headers as collections of strings

initParam A collection of all application parameter names

pageContext The javax.servlet.jsp.PageContext object for the current page

pageScope A collection of all page scope objects

param A collection of all request parameters as strings

paramValues All request parameters as collections of strings

requestScope A collection of all request scope objects

sessionScope A collection of all session scope objects

EL Example
As you can tell, web page authors can use the Expression Language without having to learn Java. Code Sample 1 shows some EL expressions as well as the use of explicit
objects.

Code Sample 1: ex1.jsp

<HTML>
<HEAD>
<TITLE>Expression Language Examples</TITLE>
</HEAD>

<BODY>

<H3>JSP Expression Language Examples</H3>


<P>
The following table illustrates some EL expressions and implicit objects:

<TABLE BORDER="1">
<THEAD>
<TD><B>Expression</B></TD>
<TD><B>Value</B></TD>
</THEAD>
<TR>
<TD>\${2 + 5}</TD>
<TD>${2 + 5}</TD>
</TD>
<TR>
<TD>\${4/5}</TD>
<TD>${4/5}</TD>
</TR>
<TR>
<TD>\${5 div 6}</TD>
<TD>${5 div 6}</TD>
</TR>
<TR>
<TD>\${5 mod 7}</TD>
<TD>${5 mod 7}</TD>
</TR>
<TR>
<TD>\${2 < 3}</TD>
<TD>${2 < 3}</TD>
</TR>
<TR>
<TD>\${2 gt 3}</TD>
<TD>${2 gt 3}</TD>
</TR>
<TR>
<TD>\${3.1 le 3.2}</TD>
<TD>${3.1 le 3.2}</TD>
</TR>
<TR>
<TD>\${(5 > 3) ? 5 : 3}</TD>
<TD>${(5 > 3) ? 5 : 3}</TD>
</TR>
<TR>
<TD>\${header["host"]}</TD>
<TD>${header["host"]}</TD>
</TR>
<TR>
<TD>\${header["user-agent"]}</TD>
<TD>${header["user-agent"]}</TD>
</TR>

</TABLE>

</BODY>
</HTML>

In order to run this, do the following. Here I assume that Tomcat 5.0 is installed at c:\Tomcat5.0

1. Change directory to c:\Tomcat5.0\webapps\jsp-examples

2. Create a directory and name it whatever you like, let's say jsp2-tutorial

3. Change directory to jsp2-tutorial

4. Copy the ex1.jsp from this article and save it there

5. Start the Tomcat 5 server by going to Start->Programs->Apache Tomcat 5.0->Start Tomcat

6. In your Web browser, enter http://localhost:8080/jsp-examples/jsp2-tutorial/ex1.jsp

You should something similar to Figure 1. It is that simple to use the Expression Language!
Figure 1: JSP Expression Language and Implicit Objects
Note: In this article, all JSP pages will be saved under c:\Tomcat5.0\webapps\jsp-examples\jsp2-tutorial.

Fill-Out-Form Example
The implicit object, $param[var] can be used to read values from a fill-out form. Code Sample 2 shows a simple example of a fill-out form that prompts the user to enter a
name.

Code Sample 2: form.jsp

<HTML>
<HEAD>
<TITLE>Form Content</TITLE>
</HEAD>

<BODY>

<H3>Fill-out-form</H3>
<P>
<FORM action="/developer/technicalArticles/javaserverpages/JSP20/form.jsp" method="GET">
Name = <input type="text" name="name" value="${param['name']}">
<input type="submit" value="Submit Name">
</FORM>

<P>
The Name is: ${param.name}

</BODY>
</HTML>

In this example, when the user enters a name and clicks the "Submit Name" button, the name entered will be displayed on the same page next to "The Name is: " as shown
in Figure 2.

Again, in order to run this example, simply copy form.jsp to c:\Tomcat5.0\webapps\jsp-examples\jsp2-tutorial and request that page from a Web browser.

Figure 2: Handling forms


Developing and Using Functions
The expression language allows you to define functions that can be invoked in an expression. Functions must be programmed as a public static method in a public
class. Once the function is developed, its signature is mapped in a Tag Library Descriptor (TLD).

To illustrate the use of functions, I use a simple example to add two numbers. First we write the Java code for the method to add two numbers. Code Sample 3 shows a
static method that accepts two Strings, parses them to integers, and returns their sum.

Code Sample 3: Compute.java

package jsp2.examples.el;
import java.util.*;

public class Compute {


public static int add(String x, String y) {
int a = 0;
int b = 0;
try {
a = Integer.parseInt(x);
b = Integer.parseInt(y);
}catch(Exception e) {}
return a + b;
}
}

Once this is successfully compiled using javac, the next step is to map the function's signature in the tag library. Code Sample 4 shows how to map the add function to the
class containing the implementation of the function and the signature of the function. I will tell you where to add this later.

Code Sample 4: Function Descriptor

<function>
<description>add x and y</description>
<name>add</name>
<function-class>jsp2.examples.el.Compute
</function-class>
<function-signature>int
add(java.lang.String,java.lang.String)
</function-signature>
</function>

Now, we can write the JSP page that uses the function. Code Sample 5 shows a form with two fields. The user enters two numbers and when the "Add Numbers" button is
clicked, the function is called to add the numbers. The result is displayed on the same page.

Code Sample 5: math.jsp

<%@ taglib prefix="my"


uri="http://jakarta.apache.org/tomcat/jsp2-example-taglib %>

<HEAD>
<TITLE>Functions</TITLE>
</HEAD>

<BODY>

<H3>Add Numbers</H3>
<P>
<FORM action="/developer/technicalArticles/javaserverpages/JSP20/math.jsp" method="GET">
X = <input type="text" name="x" value="${param["x"]}">
<BR>
Y = <input type="text" name="y" value="${param["y"]}">
<input type="submit" value="Add Numbers">
</FORM>

<P>
The sum is: ${my:add(param["x"],param["y"])}

</BODY>
</HTML>

To run this example:

1. Copy Compute.java and save it at: C:\Tomcat5.0\webapps\jsp-examples\WEB-INF\classes\jsp2\examples\el

2. Compile Compute.java using javac

3. Edit the file C:\Tomcat5.0\webapps\jsp-examples\WEB-INF\jsp2\jsp2-example-taglib.tld and append the snippet of code in Code Sample 4
after the last </function> in the file and before </taglib>

4. Copy math.jsp to c:\Tomcat5.0\webapps\jsp-examples\jsp2-tutorial

5. Request the jsp file math.jsp from a web browser

If all goes well, you should see something similar to Figure 3.

Figure 3: Using Functions


Tag Handlers
The APIs for classic tag handlers in JSP 1.2 is complicated by the allowance of scriptlets in the body of tags. With the expression language, however, it is now feasible to
develop scriptless JSP pages. To this end, JSP 2.0 has introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways:

1. Java developers: by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface.


2. Page authors who do not know Java: by using tag files.

Here is an example of the first approach. Code Sample 6 shows a simple tag handler that prints This is my first tag!.

Code Sample 6: HelloTag.java

package jsp2.examples.simpletag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

/**
* SimpleTag handler that prints "This is my first tag!"
*/
public class HelloTag extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
getJspContext().getOut().write("This is my first tag!");
}
}

Once this is successfully compiled, the next step is to define a tag descriptor in a TLD. Code Sample 7 shows a sample tag descriptor:

Code Sample 7: Tag Descriptor

<tag>
<description>Prints this is my first tag</description>
<name>hello</name>
<tag-class>jsp2.examples.simpletag.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>

And finally, Code Sample 8 shows a JSP page that uses the tag I have just developed.

Code Sample 8: helloworld.jsp

<%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %>


<HTML>
<HEAD>
<TITLE>Simple Tag Handler</TITLE>
</HEAD>

<BODY>
<H2>Simple Tag Handler</H2>
<P>
<B>My first tag prints</B>: <mytag:hello/>
</BODY>
</HTML>

To run this example:

1. Copy HelloTag.java and save it under C:\Tomcat5.0\webapps\jsp-examples\WEB-INF\classes\jsp2\examples\simpletag

2. Compile the HelloTag.java using javac

3. Append the tag description shown in Code Sample 7 to the end of the file: C:\Tomcat5.0\webapps\jsp-examples\WEB-INF\jsp2\jsp2-example-
taglib.tld, before </taglib>

4. Copy helloworld.jsp and save it at: c:\Tomcat5.0\webapps\jsp-examples\jsp2-tutorial

5. Request helloworld.jsp from a web browser

If all goes well you should see something similar to Figure 4.

Figure 4: Simple Tag Handler Example


Tag File
The other way of using the Simple Tag Extension is through the use of tag files. A tag file is a source file that provides a way for a page author to abstract a segment of JSP
code and make it reusable through a custom action. In other words, tag files allow JSP page authors to create reusable tag libraries using JSP syntax. The required file
extension for a tag file is .tag.

To demonstrate how easy this is, consider the tag file in Code Sample 9. That is right, this is a tag file!
Code Sample 9: greetings.tag

Hello there. How are you doing?


Once a tag file has been defined, you can write a JSP page that uses this custom action. As an example, consider the JSP page in Code Sample 10.

Code Sample 10: chat.jsp

<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>


<HTML>
<HEAD>
<TITLE>JSP 2.0 Examples - Hello World Using a Tag File</TITLE>
</HEAD>
<BODY>
<H2>Tag File Example</H2>
<P>
<B>The output of my first tag file is</B>: <tags:greetings/>
</BODY>
</HTML>

To run this example:

1. Copy the tag file, greetings.tag, and save it under c:\Tomcat5.0\webapps\jsp-examples\WEB-INF\tags

2. Copy the JSP page, chat.jsp, and save it at c:\Tomcat5.0\webapps\jsp-examples\jsp2-tutorial

3. Request the chat.jsp file from a Web browser

If all goes well, you should see something similar to Figure 5.

Figure 5: Simple Tag File Example


Note: What is important to notice here is that I did not need to write a TLD for the greetings tag. I just created the tag file in a special directory, and imported it using the taglib
directive, and used it!

Another Tag File Example


Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with
Tomcat 5.0. The attribute directive is analogous to the <attribute> element in the TLD; it allows for the declaration of custom action attributes.

Code Sample 11: display.tag

<%@ attribute name="color" %>


<%@ attribute name="bgcolor" %>
<%@ attribute name="title" %>
<TABLE border="0" bgcolor="${color}">
<TR>
<TD><B>${title}</B></TD>
</TR>
<TR>
<TD bgcolor="${bgcolor}">
<jsp:doBody/>
</TD>
</TR>
</TABLE>

Code Sample 12 shows a simple JSP page that uses the display tag.

Code Sample 12: newsportal.jsp

<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>


<HTML>
<HEAD>
<TITLE>Another Tag File Example</TITLE>
</HEAD>
<BODY>
<H2>News Portal: Another Tag File Example</H2>
<TABLE border="0">
<TR valign="top">
<TD>
<tags:display color="#ff0000" bgcolor="#ffc0c0"
title="Travel">
Last French Concorde Arrives in NY<br/>
Another Travel Headline<br/>
Yet Another Travel Headline<br/>
</tags:display>
</TD>
<TD>
<tags:display color="#00fc00" bgcolor="#c0ffc0"
title="Technology">
Java for in-flight entertainment<BR>
Another Technology Headline<BR>
Another Technology Headline<BR>
</tags:display>
</TD>
<TD>
<tags:display color="#ffcc11" bgcolor="#ffffcc"
title="Sports">
American Football<BR/>
NBA<BR/>
Soccer<BR/>
</tags:display>
</TD>
</TR>
</TABLE>
</BODY>
</HTML>

To run this example:

1. Copy the file display.tag and save it under c:\Tomcat5.0\webapps\jsp-examples\WEB-INF\tag

2. Copy the file newsportal.jsp and save it under c:\Tomcat5.0\webapps\jsp-examples\jsp2-tutorial

3. Request the newsportal.jsp from a Web browser

Now, you should see something similar to Figure 6.

Figure 6: Using Tag File as a Template


Conclusion
JSP 2.0 makes is easier than ever to rapidly develop and easily maintain dynamic Web pages. Despite the fact the word "Java" appears in JavaServer Pages, with JSP 2.0
page authors can develop innovative dynamic Web pages without having to learn the Java programming language. The examples shown throughout the article demonstrate
how easy it is to get started using the new features in JSP 2.0 to develop dynamic Web pages.

For More Information


• Fast Track JSP 1.2

• JavaServer Pages Technology

• JavaServer Pages Specification (JSR 152)

• The Tomcat 5 Servlet/JSP Container

• JSP Developers Forum

• JavaServer Pages Standard Tag Library (JSTL)

• Faster Development with JavaServer Pages Standard Tag Library (JSTL 1.0)
Acknowledgments
Special thanks to Gregory Murray and Mark Roth of Sun Microsystems, whose feedback helped me improve this article.

Vous aimerez peut-être aussi