Java Server Pages
Java Server Pages представляет технологию, которая позволяет создавать динамические веб-страницы. Изначально JSP (вместе с сервлетами) на заре развития Java EE являлись доминирующим подходом к веб-разработке на языке Java. И хотя в настоящее время они уступило свое место другой технологии — JSF, тем не менее JSP продолжают широко использоваться.
По сути Java Server Page или JSP представляет собой html-код с вкраплениями кода Java. В то же время станицы jsp — это не стандартные html-страницы. Когда приходит запрос к определенной странице JSP, то сервер обрабатывает ее, генерирует из нее код html и отправляет его клиенту. В итоге пользователь после обращения к странице JSP видит в своем браузере обычную html-страницу.
Как и обычные статические веб-страницы, файлы JSP необходимо размещать на веб-сервере, к которому обычные пользователи могут обращаться по протоколу http, например, набирая в адресной строке браузера нужный адрес. Однако чтобы сервер мог обрабатывать файлы JSP, он должен использовать движок JSP ( JSP engine ), который также называют JSP-контейнером. Есть множество движков JSP, и все они реализуют одну и ту же спецификацию и в целом работают одинаково. Однако тем не менее при переносе кода с одного веб-сервера на другой могут потребоваться небольшие изменения.

В данном случае для работы с JSP мы будем использовать Apache Tomcat, который одновременно является и веб-сервером и контейнером сервлетов и JSP.
Создадим простейшую страницу JSP. Для этого где-нибудь на жестком диске определим файл index.jsp . Все станицы JSP имеют расширение jsp . Откроем этот файл в любом текстовом редакторе и определим в нем следующий код:
С помощью тегов <% . %> мы можем определить код Java на странице JSP. В данном случае мы просто определяем переменную типа String, которая называется header.
Затем идет стандартный код страницы html. Чтобы внедрить код java внутрь html-страницы применяются теги <%= %> — после знака равно указывается выражение Java, результат которого будет выводиться вместо этих тегов. В данном случае, используются две таких вставки. Первая вставка — значение переменной header, которая была определена выше. Вторая вставка — выражение new java.util.Date() , которое возвращает текущую дату.
Для тех, кто знаком с веб-разработкой на PHP, это может напоминать оформление файлов php, которые также содержать код html и код php.
How JSP works in Java
When we, assumed as novice programmer, work with Java web, there are so many things to understand, or to be curious. I can list something such as annotations, jsp, servlet, spring framework, hibernate, JDBC, …
The most important thing to find out is how JSP works. Because we have to be aware of the process of JSP work. It makes our to understand the way that Java web takes actions.
Table of Contents
Introduction about JSP
JSP — Java Servlet Pages is a technology for developing webpages that supports dynamic content. This helps developers insert java code in HTML pages by making use of specidal JSP tags, most of which start with <% and end with %> .
A Java Servlet Pages component is a type of Java servlet that is designed to fulfill the role of a user interface for a Java web application. Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded embedded JSP tags with snippets of Java code inside them.
When you request a .jsp file in a suitable way, the JSP file is automatically translated into a proper Java servlet, compiled, and if successful, loaded into the servlet engine and “run” by performing a method call into the servlet class. The generated servlet code (both source and executable forms) is cached to avoid having to regenerate it unnecessarily. Just like a full blown servlet, the servlet generated from a JSP file is able to store context between invocations.
Using JSP, you can collect input from users through Webpage forms, present records from a database or another source, and create Webpages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing JavaBeans components, passing control between pages, and sharing information between requests, pages etc.
How JSP works
The above item we had introduced about JSP’s concept. In this item, we will dig into How JSP works.
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is very simple in which all template text is converted to println( ) statements and all JSP elements are converted to Java code. This code implements the corresponding dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format. The output is furthur passed on to the web server by the servlet engine inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally, the web browser handles the dynamically-generated HTML page inside the HTTP response exactly as if it were a static page.
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the JSP container assumes that the JSP hasn’t changed and that the generated servlet still matches the JSP’s contents. This makes the process more efficient than with the other scripting languages (such as PHP) and therefore faster.
JSP (Jakarta Server Pages ) Learn for new Beginners) —
Jakarta Server Pages (JSP; formerly Java Server Pages) is a collection of technologies that helps software developers create dynamically generated web pages based on HTML, XML, SOAP, or other document types. Released in 1999 by Sun Microsystems, JSP is similar to PHP and ASP, but uses the Java programming language.
It is used for creating web application. It is used to create dynamic web content. In this JSP tags are used to insert JAVA code into HTML pages.
JavaServer Page (JSP) is Java's answer to the popular Microsoft's Active Server Pages (ASP). JSP, like ASP, provides a simplified and fast mean to generate dynamic web contents. It allows you to mix static HTML with dynamically generated HTML — in the way that the business logic and the presentation are well separated.
JSP pages are more advantageous than Servlet:
They are easy to maintain.
No recompilation or redeployment is required.
JSP has access to entire API of JAVA .
JSP are extended version of Servlet.
Features of JSP —
Coding in JSP is easy :-
As it is just adding JAVA code to HTML/XML.
Reduction in the length of Code :-
In JSP we use action tags, custom tags etc.
Connection to Database is easier :-
It is easier to connect website to database and allows to read or write data easily to the database.
Make Interactive websites :-
In this we can create dynamic web pages which helps user to interact in real time environment.
Portable, Powerful, flexible and easy to maintain :-
as these are browser and server independent.
No Redeployment and No Re-Compilation :-
It is dynamic, secure and platform independent so no need to re-compilation.
Extension to Servlet :-
as it has all features of servlets, implicit objects and custom tags
Advantages of using JSP —
It does not require advanced knowledge of JAVA
It is capable of handling exceptions
Easy to use and learn
It can tags which are easy to use and understand
Implicit objects are there which reduces the length of code
It is suitable for both JAVA and non JAVA programmer.
Disadvantages of using JSP-
Difficult to debug for errors.
First time access leads to wastage of time.
It’s output is HTML which lacks features.
Chapter 5 JavaServer Pages Technology
JavaServer Pages (JSP) technology allows you to easily create web content that has both static and dynamic components. JSP technology makes available all the dynamic capabilities of Java Servlet technology but provides a more natural approach to creating static content.
The main features of JSP technology are as follows:
A language for developing JSP pages, which are text-based documents that describe how to process a request and construct a response
An expression language for accessing server-side objects
Mechanisms for defining extensions to the JSP language
JSP technology also contains an API that is used by developers of web containers, but this API is not covered in this tutorial.
What Is a JSP Page?
A JSP page is a text document that contains two types of text: static data, which can be expressed in any text-based format (such as HTML, SVG, WML, and XML), and JSP elements, which construct dynamic content.
The recommended file extension for the source file of a JSP page is .jsp. The page can be composed of a top file that includes other files that contain either a complete JSP page or a fragment of a JSP page. The recommended extension for the source file of a fragment of a JSP page is .jspf.
The JSP elements in a JSP page can be expressed in two syntaxes, standard and XML, though any given file can use only one syntax. A JSP page in XML syntax is an XML document and can be manipulated by tools and APIs for XML documents. This chapter and Chapters Chapter 7, JavaServer Pages Standard Tag Library through Chapter 9, Scripting in JSP Pages document only the standard syntax. The XML syntax is covered in Chapter 6, JavaServer Pages Documents.
A Simple JSP Page Example
The web page in Figure 5–1 is a form that allows you to select a locale and displays the date in a manner appropriate to the locale.
Figure 5–1 Localized Date Form
The source code for this example is in the tut-install /javaeetutorial5/examples/web/date/ directory. The JSP page, index.jsp , appears below; it is a typical mixture of static HTML markup and JSP elements. If you have developed web pages, you are probably familiar with the HTML document structure statements (<head>, <body>, and so on) and the HTML statements that create a form (<form>) and a menu (<select>).
The lines in bold in the example code contain the following types of JSP constructs:
A page directive ( <%@page . %> ) sets the content type returned by the page.
Tag library directives ( <%@taglib . %> ) import custom tag libraries.
jsp:useBean is a standard element that creates an object containing a collection of locales and initializes an identifier that points to that object.
JSP expression language expressions ( $ ) retrieve the value of object properties. The values are used to set custom tag attribute values and create dynamic content.
Custom tags (see Chapter 8, Custom Tags in JSP Pages) set a variable ( c:set ), iterate over a collection of locale names ( c:forEach ), and conditionally insert HTML text into the response ( c:if , c:choose , c:when , c:otherwise ).
jsp:setProperty is another standard element that sets the value of an object property.
A function ( f:equals ) tests the equality of an attribute and the current item of a collection. (A built-in == operator is usually used to test equality.)
Here is the JSP page:
To deploy the date application with NetBeans IDE, follow these steps:
Start the Application Server.
In NetBeans IDE, select File->Open Project.
In the Open Project dialog, navigate to:
Select the date folder.
Select the Open as Main Project check box.
Click Open Project.
In the Projects tab, right-click the date project, and select Undeploy and Deploy.
To deploy the date application with the Ant tool, follow these steps:
In a terminal window, go to tut-install /javaeetutorial5/examples/web/date/ .
Type ant . This command will spawn any necessary compilations, copy files to the tut-install /javaeetutorial5/examples/web/date/build/ directory, and create a WAR file.
Start the Application Server.
Type ant deploy .
To run the example, do the following:
Set the character encoding in your browser to UTF-8.
Open your browser to http://localhost:8080/date.
You will see a combo box whose entries are locales. Select a locale and click Get Date. You will see the date expressed in a manner appropriate for that locale.
Some of the characters might not display properly if you don’t have the appropriate language files installed on your machine. Consult the user guide or online help for your operating system to determine how you can install these language files.
The Example JSP Pages
To illustrate JSP technology, this chapter rewrites each servlet in the Duke’s Bookstore application introduced in The Example Servlets as a JSP page (see Table 5–1).
Enter the bookstore.
Create the bookstore banner.
Browse the books offered for sale.
Add a book to the shopping cart.
bookcatalog.jsp and bookdetails.jsp
Get detailed information on a specific book.
Display the shopping cart.
Remove one or more books from the shopping cart.
Buy the books in the shopping cart.
Receive an acknowledgment for the purchase.
The data for the bookstore application is still maintained in a database and is accessed through tut-install /javaeetutorial5/examples/web/bookstore2/src/java/com/sun/bookstore2/database/BookDBAO.java . However, the JSP pages access BookDBAO through the JavaBeans component tut-install /javaeetutorial5/examples/web/bookstore2/src/java/com/sun/bookstore2/database/BookDB.java . This class allows the JSP pages to use JSP elements designed to work with JavaBeans components (see JavaBeans Component Design Conventions).
The implementation of the database bean follows. The bean has two instance variables: the current book and the data access object.
This version of the Duke’s Bookstore application is organized along the Model-View-Controller (MVC) architecture. The MVC architecture is a widely used architectural approach for interactive applications that distributes functionality among application objects so as to minimize the degree of coupling between the objects. To achieve this, it divides applications into three layers: model, view, and controller. Each layer handles specific tasks and has responsibilities to the other layers:
The model represents business data, along with business logic or operations that govern access and modification of this business data. The model notifies views when it changes and lets the view query the model about its state. It also lets the controller access application functionality encapsulated by the model. In the Duke’s Bookstore application, the shopping cart and database access object contain the business logic for the application.
The view renders the contents of a model. It gets data from the model and specifies how that data should be presented. It updates data presentation when the model changes. A view also forwards user input to a controller. The Duke’s Bookstore JSP pages format the data stored in the session-scoped shopping cart and the page-scoped database bean.
The controller defines application behavior. It dispatches user requests and selects views for presentation. It interprets user inputs and maps them into actions to be performed by the model. In a web application, user inputs are HTTP GET and POST requests. A controller selects the next view to display based on the user interactions and the outcome of the model operations. In the Duke’s Bookstore application, the Dispatcher servlet is the controller. It examines the request URL, creates and initializes a session-scoped JavaBeans component (the shopping cart), and dispatches requests to view JSP pages.
When employed in a web application, the MVC architecture is often referred to as a Model-2 architecture. The bookstore example discussed in Chapter 4, Java Servlet Technology, which intermixes presentation and business logic, follows what is known as a Model-1 architecture. The Model-2 architecture is the recommended approach to designing web applications.
In addition, this version of the application uses several custom tags from the JavaServer Pages Standard Tag Library (JSTL), described in Chapter 7, JavaServer Pages Standard Tag Library:
c:if, c:choose, c:when, and c:otherwise for flow control
c:set for setting scoped variables
c:url for encoding URLs
fmt:message, fmt:formatNumber, and fmt:formatDate for providing locale-sensitive messages, numbers, and dates
Custom tags are the preferred mechanism for performing a wide variety of dynamic processing tasks, including accessing databases, using enterprise services such as email and directories, and implementing flow control. In earlier versions of JSP technology, such tasks were performed with JavaBeans components in conjunction with scripting elements (discussed in Chapter 9, Scripting in JSP Pages). Although still available in JSP 2.0 technology, scripting elements tend to make JSP pages more difficult to maintain because they mix presentation and logic, something that is discouraged in page design. Custom tags are introduced in Using Custom Tags and described in detail in Chapter 8, Custom Tags in JSP Pages.
Finally, this version of the example contains an applet to generate a dynamic digital clock in the banner. See Including an Applet for a description of the JSP element that generates HTML for downloading the applet.
To deploy and run the application using NetBeans IDE, follow these steps:
In NetBeans IDE, select File->Open Project.
In the Open Project dialog, navigate to:
Select the bookstore2 folder.
Select the Open as Main Project check box and the Open Required Projects check box.
Click Open Project.
In the Projects tab, right-click the bookstore2 project, and select Undeploy and Deploy.
To run the application, open the bookstore URL http://localhost:8080/bookstore2/books/bookstore.
To deploy and run the application using Ant, follow these steps:
In a terminal window, go to tut-install /javaeetutorial5/examples/web/bookstore2/ .
Type ant . This command will spawn any necessary compilations, copy files to the tut-install /javaeetutorial5/examples/web/bookstore2/build/ directory, and create a WAR file and copy it to the tut-install /javaeetutorial5/examples/web/bookstore2/dist/ directory.
Start the Application Server.
To deploy the example, type ant deploy . The deploy target outputs a URL for running the application. Ignore this URL, and instead use the one shown in the next step.
To run the application, open the bookstore URL http://localhost:8080/bookstore2/books/bookstore.
To learn how to configure the example, refer to the deployment descriptor (the web.xml file), which includes the following configurations:
A display-name element that specifies the name that tools use to identify the application.
A context-param element that specifies the JSTL resource bundle base name.
A listener element that identifies the ContextListener class used to create and remove the database access.
A servlet element that identifies the Dispatcher servlet instance.
A set of servlet-mapping elements that map Dispatcher to URL patterns for each of the JSP pages in the application.
Nested inside a jsp-config element are two jsp-property-group elements, which define the preludes and coda to be included in each page. See Setting Properties for Groups of JSP Pages for more information.
Figure 5–2 shows the bookcatalog.jsp page from the Duke’s Bookstore application. This page displays a list of all the books that are available for purchase.
Figure 5–2 Book Catalog
See Troubleshooting Duke’s Bookstore Database Problems for help with diagnosing common problems related to the database server. If the messages in your pages appear as strings of the form . Key . , the likely cause is that you have not provided the correct resource bundle base name as a context parameter.
The Life Cycle of a JSP Page
A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of JSP pages (in particular the dynamic aspects) are determined by Java Servlet technology. You will notice that many sections in this chapter refer to classes and methods described in Chapter 4, Java Servlet Technology.
When a request is mapped to a JSP page, the web container first checks whether the JSP page’s servlet is older than the JSP page. If the servlet is older, the web container translates the JSP page into a servlet class and compiles the class. During development, one of the advantages of JSP pages over servlets is that the build process is performed automatically.
Translation and Compilation
During the translation phase each type of data in a JSP page is treated differently. Static data is transformed into code that will emit the data into the response stream. JSP elements are treated as follows:
Directives are used to control how the web container translates and executes the JSP page.
Scripting elements are inserted into the JSP page’s servlet class. See Chapter 9, Scripting in JSP Pages for details.
Expression language expressions are passed as parameters to calls to the JSP expression evaluator.
jsp:[set|get]Property elements are converted into method calls to JavaBeans components.
jsp:[include|forward]elements are converted into invocations of the Java Servlet API.
The jsp:plugin element is converted into browser-specific markup for activating an applet.
Custom tags are converted into calls to the tag handler that implements the custom tag.
In the Application Server, the source for the servlet created from a JSP page named pageName is in this file:
For example, the source for the index page (named index.jsp ) for the date localization example discussed at the beginning of the chapter would be named:
Both the translation and the compilation phases can yield errors that are observed only when the page is requested for the first time. If an error is encountered during either phase, the server will return JasperException and a message that includes the name of the JSP page and the line where the error occurred.
After the page has been translated and compiled, the JSP page’s servlet (for the most part) follows the servlet life cycle described in Servlet Life Cycle:
If an instance of the JSP page’s servlet does not exist, the container:
Loads the JSP page’s servlet class
Instantiates an instance of the servlet class
Initializes the servlet instance by calling the jspInit method
The container invokes the _jspService method, passing request and response objects.
If the container needs to remove the JSP page’s servlet, it calls the jspDestroy method.
Execution
You can control various JSP page execution parameters by using page directives. The directives that pertain to buffering output and handling errors are discussed here. Other directives are covered in the context of specific page-authoring tasks throughout the chapter.
Buffering
When a JSP page is executed, output written to the response object is automatically buffered. You can set the size of the buffer using the following page directive:
A larger buffer allows more content to be written before anything is actually sent back to the client, thus providing the JSP page with more time to set appropriate status codes and headers or to forward to another web resource. A smaller buffer decreases server memory load and allows the client to start receiving data more quickly.
Handling JSP Page Errors
Any number of exceptions can arise when a JSP page is executed. To specify that the web container should forward control to an error page if an exception occurs, include the following page directive at the beginning of your JSP page:
The Duke’s Bookstore application page tut-install /javaeetutorial5/examples/web/bookstore2/web/template/preludeErrorPage.jspf contains the directive:
The following page directive at the beginning of tut-install /javaeetutorial5/examples/web/bookstore2/web/error/errorpage.jsp indicates that it is serving as an error page:
This directive makes an object of type javax.servlet.jsp.ErrorData available to the error page so that you can retrieve, interpret, and possibly display information about the cause of the exception in the error page. You access the error data object in an EL (see Unified Expression Language) expression by way of the page context. Thus, $ retrieves the status code, and $ retrieves the exception. You can retrieve the cause of the exception using this expression:
For example, the error page for Duke’s Bookstore is as follows:
You can also define error pages for the WAR that contains a JSP page. If error pages are defined for both the WAR and a JSP page, the JSP page’s error page takes precedence.
Creating Static Content
You create static content in a JSP page simply by writing it as if you were creating a page that consisted only of that content. Static content can be expressed in any text-based format, such as HTML, Wireless Markup Language (WML), and XML. The default format is HTML. If you want to use a format other than HTML, at the beginning of your JSP page you include a page directive with the contentType attribute set to the content type. The purpose of the contentType directive is to allow the browser to correctly interpret the resulting content. So if you wanted a page to contain data expressed in WML, you would include the following directive:
A registry of content type names is kept by the IANA at http://www.iana.org/assignments/media-types/.
Response and Page Encoding
You also use the contentType attribute to specify the encoding of the response. For example, the date application specifies that the page should be encoded using UTF-8, an encoding that supports almost all locales, using the following page directive:
If the response encoding weren’t set, the localized dates would not be rendered correctly.
To set the source encoding of the page itself, you would use the following page directive:
You can also set the page encoding of a set of JSP pages. The value of the page encoding varies depending on the configuration specified in the JSP configuration section of the web application deployment descriptor (see Declaring Page Encodings).
Creating Dynamic Content
You create dynamic content by accessing Java programming language object properties.
Using Objects within JSP Pages
You can access a variety of objects, including enterprise beans and JavaBeans components, within a JSP page. JSP technology automatically makes some objects available, and you can also create and access application-specific objects.
Using Implicit Objects
Implicit objects are created by the web container and contain information related to a particular request, page, session, or application. Many of the objects are defined by the Java servlet technology underlying JSP technology and are discussed at length in Chapter 4, Java Servlet Technology. The section Implicit Objects explains how you access implicit objects using the JSP expression language.
Using Application-Specific Objects
When possible, application behavior should be encapsulated in objects so that page designers can focus on presentation issues. Objects can be created by developers who are proficient in the Java programming language and in accessing databases and other services. The main way to create and use application-specific objects within a JSP page is to use JSP standard tags (discussed in JavaBeans Components) to create JavaBeans components and set their properties, and EL expressions to access their properties. You can also access JavaBeans components and other objects in scripting elements, which are described in Chapter 9, Scripting in JSP Pages.
Using Shared Objects
The conditions affecting concurrent access to shared objects (described in Controlling Concurrent Access to Shared Resources) apply to objects accessed from JSP pages that run as multithreaded servlets. You can use the following page directive to indicate how a web container should dispatch multiple client requests:
When the isThreadSafe attribute is set to true, the web container can choose to dispatch multiple concurrent client requests to the JSP page. This is the default setting. If using true, you must ensure that you properly synchronize access to any shared objects defined at the page level. This includes objects created within declarations, JavaBeans components with page scope, and attributes of the page context object (see Implicit Objects).
If isThreadSafe is set to false, requests are dispatched one at a time in the order they were received, and access to page-level objects does not have to be controlled. However, you still must ensure that access is properly synchronized to attributes of the application or session scope objects and to JavaBeans components with application or session scope. Furthermore, it is not recommended to set isThreadSafe to false. The JSP page’s generated servlet will implement the javax.servlet.SingleThreadModel interface, and because the Servlet 2.4 specification deprecates SingleThreadModel, the generated servlet will contain deprecated code.
Unified Expression Language
The primary new feature of JSP 2.1 is the unified expression language (unified EL), which represents a union of the expression language offered by JSP 2.0 and the expression language created for JavaServer Faces technology (see Chapter 10, JavaServer Faces Technology) version 1.0.
The expression language introduced in JSP 2.0 allows page authors to use simple expressions to dynamically read data from JavaBeans components. For example, the test attribute of the following conditional tag is supplied with an EL expression that compares the number of items in the session-scoped bean named cart with 0.
As explained in The Life Cycle of a JSP Page, JSP supports a simple request/response life cycle, during which a page is executed and the HTML markup is rendered immediately. Therefore, the simple, read-only expression language offered by JSP 2.0 was well suited to the needs of JSP applications.
JavaServer Faces technology, on the other hand, features a multiphase life cycle designed to support its sophisticated UI component model, which allows for converting and validating component data, propagating component data to objects, and handling component events. To facilitate these functions, JavaServer Faces technology introduced its own expression language that included the following functionality:
Deferred evaluation of expressions
The ability to set data as well as get data
The ability to invoke methods
See Using the Unified EL to Reference Backing Beans for more information on how to use the unified EL in JavaServer Faces applications.
These two expression languages have been unified for a couple reasons. One reason is so that page authors can mix JSP content with JavaServer Faces tags without worrying about conflicts caused by the different life cycles these technologies support. Another reason is so that other JSP-based technologies could make use of the additional features similarly to the way JavaServer Faces technology uses them. In fact, although the standard JSP tags and static content continue to use only those features present in JSP 2.0, authors of JSP custom tags can create tags that take advantage of the new set of features in the unified expression language.
To summarize, the new, unified expression language allows page authors to use simple expressions to perform the following tasks:
Dynamically read application data stored in JavaBeans components, various data structures, and implicit objects
Dynamically write data, such as user input into forms, to JavaBeans components
Invoke arbitrary static and public methods
Dynamically perform arithmetic operations
The unified EL also allows custom tag developers to specify which of the following kinds of expressions that a custom tag attribute will accept:
Immediate evaluation expressions or deferred evaluation expressions. An immediate evaluation expression is evaluated immediately by the JSP engine. A deferred evaluation expression can be evaluated later by the underlying technology using the expression language.
Value expression or method expression. A value expression references data, whereas a method expression invokes a method.
Rvalue expression or Lvalue expression. An rvalue expression can only read a value, whereas an lvalue expression can both read and write that value to an external object.
Finally, the unified EL also provides a pluggable API for resolving expressions so that application developers can implement their own resolvers that can handle expressions not already supported by the unified EL.
This section gives an overview of the unified expression language features by explaining the following topics:
Immediate and Deferred Evaluation Syntax
The unified EL supports both immediate and deferred evaluation of expressions. Immediate evaluation means that the JSP engine evaluates the expression and returns the result immediately when the page is first rendered. Deferred evaluation means that the technology using the expression language can employ its own machinery to evaluate the expression sometime later during the page’s life cycle, whenever it is appropriate to do so.
Those expressions that are evaluated immediately use the $<> syntax, which was introduced with the JSP 2.0 expression language. Expressions whose evaluation is deferred use the #<> syntax, which was introduced by JavaServer Faces technology.
Because of its multiphase life cycle, JavaServer Faces technology uses deferred evaluation expressions. During the life cycle, component events are handled, data is validated, and other tasks are performed, all done in a particular order. Therefore, it must defer evaluation of expressions until the appropriate point in the life cycle.
Other technologies using the unified EL might have different reasons for using deferred expressions.
Immediate Evaluation
All expressions using the $<> syntax are evaluated immediately. These expressions can only be used within template text or as the value of a JSP tag attribute that can accept runtime expressions.
The following example shows a tag whose value attribute references an immediate evaluation expression that gets the total price from the session-scoped bean named cart:
The JSP engine evaluates the expression, $ , converts it, and passes the returned value to the tag handler.
Immediate evaluation expressions are always read-only value expressions. The expression shown above can only get the total price from the cart bean; it cannot set the total price.
Deferred Evaluation
Deferred evaluation expressions take the form # and can be evaluated at other phases of a page life cycle as defined by whatever technology is using the expression. In the case of JavaServer Faces technology, its controller can evaluate the expression at different phases of the life cycle depending on how the expression is being used in the page.
The following example shows a JavaServer Faces inputText tag, which represents a text field component into which a user enters a value. The inputText tag’s value attribute references a deferred evaluation expression that points to the name property of the customer bean.
For an initial request of the page containing this tag, the JavaServer Faces implementation evaluates the # expression during the render response phase of the life cycle. During this phase, the expression merely accesses the value of name from the customer bean, as is done in immediate evaluation.
For a postback, the JavaServer Faces implementation evaluates the expression at different phases of the life cycle, during which the value is retrieved from the request, validated, and propagated to the customer bean.
As shown in this example, deferred evaluation expressions can be value expressions that can be used to both read and write data. They can also be method expressions. Value expressions (both immediate and deferred) and method expressions are explained in the next section.
Value and Method Expressions
The unified EL defines two kinds of expressions: value expressions and method expressions. Value expressions can either yield a value or set a value. Method expressions reference methods that can be invoked and can return a value.
Value Expressions
Value expressions can be further categorized into rvalue and lvalue expressions. Rvalue expressions are those that can read data, but cannot write it. Lvalue expressions can both read and write data.
All expressions that are evaluated immediately use the $<> delimiters and are always rvalue expressions. Expressions whose evaluation can be deferred use the #<> delimiters and can act as both rvalue and lvalue expressions. Consider these two value expressions:
The former uses immediate evaluation syntax, whereas the latter uses deferred evaluation syntax. The first expression accesses the name property, gets its value, and the value is added to the response and rendered on the page. The same thing can happen with the second expression. However, the tag handler can defer the evaluation of this expression to a later time in the page life cycle, if the technology using this tag allows it.
In the case of JavaServer Faces technology, the latter tag’s expression is evaluated immediately during an initial request for the page. In this case, this expression acts as an rvalue expression. During a postback, this expression can be used to set the value of the name property with user input. In this situation, the expression acts as an lvalue expression.
Referencing Objects Using Value Expressions
Both rvalue and lvalue expressions can refer to the following objects and their properties or attributes:
Java SE enumerated types
See Implicit Objects for more detail on the implicit objects available with JSP technology.
To refer to these objects, you write an expression using a variable name with which you created the object. The following expression references a JavaBeans component called customer.
The web container evaluates a variable that appears in an expression by looking up its value according to the behavior of PageContext.findAttribute(String), where the String argument is the name of the variable. For example, when evaluating the expression $ , the container will look for customer in the page, request, session, and application scopes and will return its value. If customer is not found, null is returned. A variable that matches one of the implicit objects described in Implicit Objects will return that implicit object instead of the variable’s value.
You can alter the way variables are resolved with a custom EL resolver, which is a new feature of the unified EL. For instance, you can provide an EL resolver that intercepts objects with the name customer, so that $ returns a value in the EL resolver instead. However, you cannot override implicit objects in this way. See EL Resolvers for more information on EL resolvers.
You can set the variable name, customer, when you declare the bean. See Creating and Using a JavaBeans Component for information on how to declare a JavaBeans component for use in your JSP pages.
To declare beans in JavaServer Faces applications, you use the managed bean facility. See Backing Beans for information on how to declare beans for use in JavaServer Faces applications.
When referencing an enum constant with an expression, you use a String literal. For example, consider this Enum class:
To refer to the Suit constant, Suit.hearts with an expression, you use the String literal, "hearts". Depending on the context, the String literal is converted to the enum constant automatically. For example, in the following expression in which mySuit is an instance of Suit, "hearts" is first converted to a Suit.hearts before it is compared to the instance.
Referring to Object Properties Using Value Expressions
To refer to properties of a bean or an Enum instance, items of a collection, or attributes of an implicit object, you use the . or [] notation, which is similar to the notation used by ECMAScript.
So, if you wanted to reference the name property of the customer bean, you could use either the expression $ or the expression $ . The part inside the square brackets is a String literal that is the name of the property to reference.
You can use double or single quotes for the String literal. You can also combine the [] and . notations, as shown here:
Properties of an enum can also be referenced in this way. However, as with JavaBeans component properties, the Enum class’s properties must follow JavaBeans component conventions. This means that a property must at least have an accessor method called get<Property> (where <Property> is the name of the property) so that an expression can reference it.
For example, say you have an Enum class that encapsulates the names of the planets of our galaxy and includes a method to get the mass of a planet. You can use the following expression to reference the method getMass of the Planet Enum class:
If you are accessing an item in an array or list, you must use either a literal value that can be coerced to int or the [] notation with an int and without quotes. The following examples could all resolve to the same item in a list or array, assuming that socks can be coerced to int:
In contrast, an item in a Map can be accessed using a string literal key; no coercion is required:
An rvalue expression also refers directly to values that are not objects, such as the result of arithmetic operations and literal values, as shown by these examples:
The unified expression language defines the following literals:
Integer: as in Java
Floating point: as in Java
String: with single and double quotes; " is escaped as \", ’ is escaped as \', and \ is escaped as \\
You can also write expressions that perform operations on an enum constant. For example, consider the following Enum class:
After declaring an enum constant called mySuit, you can write the following expression to test if mySuit is spade:
When the EL resolving mechanism resolves this expression it will invoke the valueOf method of the Enum class with the Suit class and the spade type, as shown here:
See JavaBeans Components for more information on using expressions to reference JavaBeans components and their properties.
Where Value Expressions Can Be Used
Value expressions using the $<> delimiters can be used in the following places:
In any standard or custom tag attribute that can accept an expression
The value of an expression in static text is computed and inserted into the current output. Here is an example of an expression embedded in static text:
If the static text appears in a tag body, note that an expression will not be evaluated if the body is declared to be tagdependent (see Tags with Attributes).
Lvalue expressions can only be used in tag attributes that can accept lvalue expressions.
There are three ways to set a tag attribute value using either an rvalue or lvalue expression:
With a single expression construct:
These expressions are evaluated and the result is coerced to the attribute’s expected type.
With one or more expressions separated or surrounded by text:
These kinds of expression are called a composite expressions. They are evaluated from left to right. Each expression embedded in the composite expression is coerced to a String and then concatenated with any intervening text. The resulting String is then coerced to the attribute’s expected type.
This expression is called a literal expression. In this case, the attribute’s String value is coerced to the attribute’s expected type. Literal value expressions have special syntax rules. See Literal Expressions for more information. When a tag attribute has an enum type, the expression that the attribute uses must be a literal expression. For example, the tag attribute can use the expression "hearts" to mean Suit.hearts. The literal is coerced to Suit and the attribute gets the value Suit.hearts.
All expressions used to set attribute values are evaluated in the context of an expected type. If the result of the expression evaluation does not match the expected type exactly, a type conversion will be performed. For example, the expression $ provided as the value of an attribute of type float will result in the following conversion:
See section 1.18 of the JavaServer Pages 2.1 Expression Language Specification (available from http://jcp.org/aboutJava/communityprocess/final/jsr245/) for the complete type conversion rules.
Method Expressions
Another feature of the unified expression language is its support of deferred method expressions. A method expression is used to invoke an arbitrary public method, which can return a result. A similar feature of the unified EL is functions. Method expressions differ from functions in many ways. Functions explains more about the differences between functions and method expressions.
Method expressions primarily benefit JavaServer Faces technology, but they are available to any technology that can support the unified expression language. Let’s take a look at how JavaServer Faces technology employs method expressions.
In JavaServer Faces technology, a component tag represents a UI component on a page. The component tag uses method expressions to invoke methods that perform some processing for the component. These methods are necessary for handling events that the components generate and validating component data, as shown in this example:
The inputText tag displays a UIInput component as a text field. The validator attribute of this inputText tag references a method, called validateName, in the bean, called customer. The TLD (see Tag Library Descriptors) that defines the inputText tag specifies what signature the method referred to by the validator attribute must have. The same is true of the customer.submit method referenced by the action attribute of the commandButton tag. The TLD specifies that the submit method must return an Object instance that specifies which page to navigate to next after the button represented by the commandButton tag is clicked.
The validation method is invoked during the process validation phase of the life cycle, whereas the submit method is invoked during the invoke application phase of the life cycle. Because a method can be invoked during different phases of the life cycle, method expressions must always use the deferred evaluation syntax.
Similarly to lvalue expressions, method expressions can use the . and [] operators. For example, # is equivalent to # . The literal inside the [] is coerced to String and is used to find the name of the method that matches it. Once the method is found, it is invoked or information about the method is returned.
Method expressions can be used only in tag attributes and only in the following ways:
With a single expression construct, where bean refers to a JavaBeans component and method refers to a method of the JavaBeans component:
The expression is evaluated to a method expression, which is passed to the tag handler. The method represented by the method expression can then be invoked later.
Method expressions support literals primarily to support action attributes in JavaServer Faces technology. When the method referenced by this method expression is invoked, it returns the String literal, which is then coerced to the expected return type, as defined in the tag’s TLD.
Defining a Tag Attribute Type
As explained in the previous section, all kinds of expressions can be used in tag attributes. Which kind of expression and how that expression is evaluated (whether immediately or deferred) is determined by the type attribute of the tag’s definition in the TLD (see Tag Library Descriptors) file that defines the tag.
If you plan to create custom tags (see Chapter 8, Custom Tags in JSP Pages), you need to specify for each tag in the TLD what kind of expression it accepts. Table 5–2 shows the three different kinds of tag attributes that accept EL expressions, and gives examples of expressions they accept and the type definitions of the attributes that must be added to the TLD. You cannot use #<> syntax for a dynamic attribute, meaning an attribute that accepts dynamically-calculated values at runtime. Section 2.3.2 of the JavaServer Pages 2.1 specification refers to these attributes. Neither can you use the $<> syntax for a deferred attribute.