100% found this document useful (3 votes)
8 views

Mastering JavaServer Faces 2 2 Leonard Anghel instant download

Mastering JavaServer Faces 2.2 by Leonard Anghel is a comprehensive guide for implementing user interfaces using JSF 2.2. The book covers various topics including Expression Language, communication in JSF, JSF scopes, and configurations using XML and annotations. It is published by Packt Publishing and includes contributions from several reviewers with extensive experience in Java development.

Uploaded by

flochhtreva6u
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
8 views

Mastering JavaServer Faces 2 2 Leonard Anghel instant download

Mastering JavaServer Faces 2.2 by Leonard Anghel is a comprehensive guide for implementing user interfaces using JSF 2.2. The book covers various topics including Expression Language, communication in JSF, JSF scopes, and configurations using XML and annotations. It is published by Packt Publishing and includes contributions from several reviewers with extensive experience in Java development.

Uploaded by

flochhtreva6u
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Mastering JavaServer Faces 2 2 Leonard Anghel

download

https://textbookfull.com/product/mastering-javaserver-
faces-2-2-leonard-anghel/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

JavaServer Faces Introduction by Example Juneau Josh

https://textbookfull.com/product/javaserver-faces-introduction-
by-example-juneau-josh/

Pro Hibernate and MongoDB The Expert s Voice Leonard


Anghel

https://textbookfull.com/product/pro-hibernate-and-mongodb-the-
expert-s-voice-leonard-anghel/

The Definitive Guide to JSF in Java EE 8: Building Web


Applications with JavaServer Faces Bauke Scholtz

https://textbookfull.com/product/the-definitive-guide-to-jsf-in-
java-ee-8-building-web-applications-with-javaserver-faces-bauke-
scholtz/

Spring Boot Persistence Best Practices: Optimize Java


Persistence Performance in Spring Boot Applications 1st
Edition Anghel Leonard

https://textbookfull.com/product/spring-boot-persistence-best-
practices-optimize-java-persistence-performance-in-spring-boot-
applications-1st-edition-anghel-leonard/
Java Coding Problems: Become an expert Java programmer
by solving over 200 brand-new, modern, real-world
problems, 2nd edition Anghel Leonard

https://textbookfull.com/product/java-coding-problems-become-an-
expert-java-programmer-by-solving-over-200-brand-new-modern-real-
world-problems-2nd-edition-anghel-leonard/

Java Coding Problems, 2nd Edition: Become an expert


Java programmer by solving over 200 brand-new, modern,
real-world problems Anghel Leonard

https://textbookfull.com/product/java-coding-problems-2nd-
edition-become-an-expert-java-programmer-by-solving-
over-200-brand-new-modern-real-world-problems-anghel-leonard/

Mastering Embedded Linux Programming Second Edition


Unleash the full potential of Embedded Linux with Linux
4 9 and Yocto Project 2 2 Morty Updates Chris Simmonds

https://textbookfull.com/product/mastering-embedded-linux-
programming-second-edition-unleash-the-full-potential-of-
embedded-linux-with-linux-4-9-and-yocto-project-2-2-morty-
updates-chris-simmonds/

MASTERING PFSENSE 2 4 master the art of managing


securing and monitoring your on premises and cloud
network using the powerful pfsense 2 4 3 Zientara

https://textbookfull.com/product/mastering-pfsense-2-4-master-
the-art-of-managing-securing-and-monitoring-your-on-premises-and-
cloud-network-using-the-powerful-pfsense-2-4-3-zientara/

■■■ ■■■ 2 Vitamin Korean 2 1st Edition Cho Jungsoon

https://textbookfull.com/product/%eb%b9%84%ed%83%80%eb%af%bc-
%ed%95%9c%ea%b5%ad%ec%96%b4-2-vitamin-korean-2-1st-edition-cho-
jungsoon/
Mastering JavaServer
Faces 2.2

Master the art of implementing user interfaces


with JSF 2.2

Anghel Leonard

BIRMINGHAM - MUMBAI
Mastering JavaServer Faces 2.2

Copyright © 2014 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either expressed or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: June 2014

Production reference: 1190614

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78217-646-6

www.packtpub.com

Cover image by Pratyush Mohanta (tysoncinematics@gmail.com)


Credits

Author Copy Editors


Anghel Leonard Laxmi Subramanian

Reviewers Project Coordinator


Mert Çalışkan Akash Poojary
Michael Kurz
Thierry Leriche-Dessirier Proofreaders
Simran Bhogal
Michael Müller
Ameesha Green
Luca Preziati
Paul Hindle

Commissioning Editor Samantha Lyon


Owen Roberts Lucy Rowland

Acquisition Editor Indexers


Owen Roberts Hemangini Bari
Mehreen Deshmukh
Content Development Editor Tejal Soni
Sriram Neelakantan

Graphics
Technical Editors Valentina Dsilva
Krishnaveni Haridas
Taabish Khan Production Coordinator
Pramod Kumavat Arvindkumar Gupta
Mukul Pawar
Siddhi Rane Cover Work
Arvindkumar Gupta
About the Author

Anghel Leonard is a senior Java developer with more than 13 years of


experience in Java SE, Java EE, and related frameworks. He has written and
published more than 50 articles about Java technologies and more than 500 tips
and tricks for many websites that are dedicated to programming. In addition,
he has written the following books:

• Tehnologii XML XML în Java, Albastra


• Jboss Tools 3 Developer's Guide, Packt Publishing
• JSF 2.0 Cookbook, Packt Publishing
• JSF 2.0 Cookbook: LITE, Packt Publishing
• Pro Java 7 NIO.2, Apress
• Pro Hibernate and MongoDB, Apress

Currently, Anghel is developing web applications using the latest Java technologies
on the market (EJB 3.0, CDI, Spring, JSF, Struts, Hibernate, and so on). Over the
past two years, he's focused on developing rich Internet applications for geographic
information systems.
About the Reviewers

Mert Çalışkan is a principal software architect living in Ankara, Turkey. He has


over 10 years of expertise in software development with the architectural design of
Enterprise Java web applications. He is an open source advocate for software projects
such as PrimeFaces, and has also been a committer and founder to various others.
He is the co-author of PrimeFaces Cookbook, Packt Publishing, which is the first book to
be written on PrimeFaces. He is the co-author of Beginning Spring, Wiley Publications.
He is also working as an author for RebelLabs. He shares his knowledge and ideas
at local and international conferences such as JavaOne2014, JavaOne2013, JDC2010,
and JSFDays2008. He is also a member of the OpenLogic Expert Community and the
Apache Software Foundation.

I would like to thank my family, my beloved angel Funda, our


advisers at Packt Publishing, and Anghel Leonard, the author
of this great book.
Michael Kurz studied computer science at the Technical University of Vienna.
Since then, his main professional focus has been on web development, especially
in the Java EE domain. In 2007, he started working as a senior software developer
for Irian Solutions in Vienna, Austria. His main focus there is to develop JSF and
Java EE applications for various customers in Austria, Germany, and Switzerland.
Additionally, he also does JSF trainings, talks at international conferences, and is
an Apache MyFaces committer.

Besides his work as a software developer, he also likes to write about JSF-related
techniques. In November 2009, his first book JavaServer Faces 2.0, dpunkt.verlag was
published, followed by the updated edition JavaServer Faces 2.2 in November 2013
by the same publisher.

Furthermore, he is responsible for the contents of the German online JSF tutorial
at http://jsfatwork.irian.at provided by Irian, and he also writes about
JSF-related techniques in his blog at http://jsflive.wordpress.com.

Thierry Leriche-Dessirier works as a freelance JEE consultant in Paris. He


has 20 years of experience in web and Agile development domains. He teaches
software engineering at ESIEA, and in between two baby bottles, he also writes
for blogs and magazines.
Michael Müller is an IT professional with more than 30 years of experience
including about 25 years in the healthcare sector. During this time, he has worked in
different areas, especially project and product management, consulting, and software
development. He gained international knowledge not only by targeting international
markets, but also by leading external teams (from Eastern Europe and India).

Currently, he is the head of software development at the German DRG institute


(http://inek.org). In this role, he is responsible for web, Java, and .NET projects.
Web projects are preferably built with Java technologies such as JSF and JavaScript.
He is a JSF professional user and a member of the JSR 344 (JSF) expert group.

He frequently reads books and writes reviews as well as technical papers,


which are mostly published in German-printed magazines and on his website
at http://it-rezension.de. Besides that, he regularly blogs about software
development at http://blog.mueller-bruehl.de.

Michael has done technical reviewing for Java 8 in Action, Manning Publications Co.

To my wife Claudia and my children: thank you for your patience


during night reading and other long sessions. I love you!

Luca Preziati lives in Milan and has worked for six years as a Java consultant,
focusing the past five years on document management systems handling massive
volumes of data. In 2014, he joined GFT Italia full time. He has considerable
experience with both Alfresco and Documentum, as well as Liferay and Kettle.
In his free time, he enjoys swimming, biking, playing the guitar, and wine tasting
with his girlfriend.

I would like to thank all of my mentors: my parents, Ernesto and


Clelia, who taught me much about work while running their own
business (www.mintel.it); my brothers, Alessio and Stefano; and
my girlfriend, Arianna.
www.PacktPub.com

Support files, eBooks, discount offers, and more


You might want to visit www.PacktPub.com for support files and downloads related to
your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub
files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
service@packtpub.com for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
TM

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can access, read, and search across Packt's entire library of books.

Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via web browser

Free access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine entirely free books. Simply use your login credentials for
immediate access.

Instant updates on new Packt books


Get notified! Find out when new books are published by following @PacktEnterprise on
Twitter, or the Packt Enterprise Facebook page.
Table of Contents
Preface 1
Chapter 1: Dynamic Access to JSF Application Data through
Expression Language (EL 3.0) 7
EL syntax 8
EL operators 8
EL precedence of operators 9
EL reserved words 9
EL immediate and deferred evaluation 10
EL value expressions 10
Referencing a managed bean 10
Referencing a managed bean's properties 12
Referencing a managed bean's nested properties 13
Referencing Java SE enumerated types 15
Referencing collections 16
EL implicit objects 17
EL method expressions 19
The conditional text in JSF 21
Writing a custom EL resolver 26
EL 3.0 overview 35
Working with the assignment operator 36
Working with the string concatenation operator 36
Working with the semicolon operator 36
Exploring lambda expressions 36
Working with collection objects 38
Summary 40
Chapter 2: Communication in JSF 41
Passing and getting parameters 42
Using context parameters 42
Table of Contents

Passing request parameters with the <f:param> tag 42


Working with view parameters 46
Calling actions on GET requests 53
Passing attributes with the <f:attribute> tag 58
Setting property values via action listeners 61
Passing parameters using the Flash scope 64
Replacing the <f:param> tag with the JSTL <c:set> tag 69
Sending data through cookies 70
Working with hidden fields 72
Sending passwords 72
Accessing UI component attributes programmatically 73
Passing parameters via method expressions 74
Communicating via the binding attribute 75
Managed bean communication 76
Injecting a managed bean into another bean 77
Communication between managed beans using the
application/session map 78
Accessing other managed beans programmatically 80
Summary 82
Chapter 3: JSF Scopes – Lifespan and Use in Managed
Beans Communication 83
JSF scopes versus CDI scopes 83
The request scope 86
The session scope 90
The view scope 92
The application scope 94
The conversation scope 96
The flow scope 100
The simple flow 104
Flows with beans 107
Nested flows 110
Configuring flows programmatically 114
Flows and navigation cases 116
Inspecting flow navigation cases 119
Using the initializer and finalizer 120
Using the flow switch 123
Packaging flows 125
Programmatic flow scope 126
Dependent pseudo-scope 130
The none scope 131

[ ii ]
Table of Contents

The custom scope 131


Writing the custom scope class 132
Resolving a custom scope EL expression 133
Controlling the custom scope lifespan with action listeners 137
Controlling the custom scope lifespan with the navigation handler 139
Managed bean instantiation 142
Beans injection 142
Summary 145
Chapter 4: JSF Configurations Using XML
Files and Annotations – Part 1 147
JSF 2.2 new namespaces 148
JSF 2.2 programmatic configuration 149
Configuring managed beans in XML 150
Working with multiple configuration files 156
Configuring locales and resource bundles 158
Configuring validators and converters 160
Configuring navigation 168
Implicit navigation 169
Conditional navigation 172
Preemptive navigation 174
Programmatic Navigation 176
Configuring action listeners 178
Application action listeners 180
Configuring system event listeners 183
Using <f:event> 183
Implementing SystemEventListener 185
Configuring phase listeners 191
Working with @ListenerFor and @ListenersFor 196
Summary 197
Chapter 5: JSF Configurations Using XML
Files and Annotations – Part 2 199
Configuring resource handlers 200
Adding CSS and JS resources programmatically 207
Configuring the view handler 208
Overriding JSF renders 212
Working with client behavior functionality 218
JSF factories 223
Configuring the global exception handler 224
Configuring RenderKit factory 227
Configuring PartialViewContext 229

[ iii ]
Table of Contents

Configuring visitContext 232


Configuring ExternalContext 235
Configuring Flash 239
JSF 2.2 Window ID API 240
Configuring lifecycle 246
Configuring the application 250
Configuring VDL 252
Combined power of multiple factories 254
Summary 255
Chapter 6: Working with Tabular Data 257
Creating a simple JSF table 258
The CollectionDataModel class of JSF 2.2 261
Sorting tables 266
Sorting and DataModel – CollectionDataModel 272
Deleting a table row 275
Editing/updating a table row 277
Adding a new row 280
Displaying row numbers 282
Selecting a single row 283
Selecting multiple rows 285
Nesting tables 287
Paginating tables 288
Generating tables with the JSF API 295
Filtering tables 300
Styling tables 306
Alternate row colors with the rowclasses attribute 306
Highlighting rows on mouse hover 307
Highlighting rows on mouse click 308
Summary 309
Chapter 7: JSF and AJAX 311
A brief overview of the JSF-AJAX lifecycle 312
A simple JSF-AJAX example to get started 312
The JSF-AJAX attributes 313
The execute and render attributes 314
The listener attribute 316
The event attribute 317
The onevent attribute – monitoring AJAX state on client 318
The onerror attribute – monitoring AJAX errors on client 320
Grouping components under <f:ajax> tag 322
Updating input fields with AJAX after validation error 323

[ iv ]
Table of Contents

The Cancel and Clear buttons 325


Value submitted to a view scoped managed bean 326
Value submitted to a request scoped managed bean 327
Mixing AJAX and flow scope 329
Postback and AJAX 333
Postback request's conditional rendering/executing 335
Is it a non-AJAX request? 338
AJAX and <f:param> 340
Queue control for AJAX requests 340
Explicit loading of jsf.js 342
Depicting the params value 343
Non-UICommand components and jsf.ajax.request 344
Customizing jsf.js 347
AJAX and the progress bar/indicator 350
Summary 352
Chapter 8: JSF 2.2 – HTML5 and Upload 353
Working with HTML5 and JSF 2.2 353
Pass-through attributes 354
Pass-through elements 356
JSF 2.2 – HTML5 and Bean Validation 1.1 (Java EE 7) 358
JSF 2.2 upload feature 359
A simple JSF 2.2 upload example 361
Using multiple <h:inputFile> elements 363
Extracting info about a file to be uploaded 364
Writing uploaded data to a disk 366
Upload validator 368
Ajaxify the upload 369
Uploading images with preview 370
Uploading multiple files 378
Upload and the indeterminate progress bar 381
Upload and the determinate progress bar 383
Summary 387
Chapter 9: JSF State Management 389
JSF saving the view state 389
JSF partial saving view state 390
Partial state saving and tree visiting 390
JSF saving view state on the server or client 391
JSF logical and physical views 394
Saving the state in a database – an experimental application 395
Writing the custom ResponseStateManager class 398
Adding MongoDB in equation 400

[v]
Table of Contents

Handling ViewExpiredException 403


Server-state serialization in a session 406
JSF 2.2 is stateless 407
The view scoped beans and the stateless feature 409
Detecting stateless views programmatically 411
JSF security notes 411
Cross-site request forgery (CSRF) 412
Cross-site scripting (XSS) 412
SQL injection 412
Summary 413
Chapter 10: JSF Custom Components 415
Building noncomposite custom components 416
Writing a custom tag handler 419
Dissecting a custom component 420
Custom component implementation 423
Building composite components 433
Developing the Temperature composite component 436
Transforming a jQuery component into composite component 440
Writing the HTML5 date picker as a composite component 446
Decorating an image with actions 450
Working with composite facets 452
Validating/converting inputs inside composite components 454
Checking the presence of an attribute 456
Composite components' pitfalls 456
Null values within a composite component's attributes 456
Hiding pass-through attributes in composite components 457
Counting the children of a composite component 459
Top-level component's pitfall 460
Distributing composite components as JARs in JSF 2.2 461
Adding composite components programmatically 463
Summary 465
Chapter 11: JSF 2.2 Resource Library Contracts – Themes 467
Working with contracts 468
Styling tables with contracts 471
Styling UI components with contracts 474
Styling contracts across different devices 476
Writing contracts for composite components 481
Writing a theme switcher 483
Configuring contracts in XML 491
Packaging contracts in JARs 492
Summary 493

[ vi ]
Table of Contents

Chapter 12: Facelets Templating 495


A brief overview of the Facelets tags 495
Creating a simple template – PageLayout 498
Passing parameters via <ui:param> 501
Passing bean properties and action methods via <ui:param> 503
Exploiting the <ui:decorate> and <ui:fragment> tags 505
Iterating with <ui:repeat> 508
Working with <ui:include> and <f:viewParam> 511
Working with <ui:include> and <ui:param> 513
Debugging with <ui:debug> 516
Removing the content with <ui:remove> 516
Using the jsfc attribute 518
Extending the PageLayout template 519
Facelets' programmatic aspects 524
FaceletFactory considerations 524
Working with FaceletCache 524
ResourceResolver swallowed by ResourceHandler 527
Include Facelets programmatically 531
Creating a TagHandler class 532
Writing custom Facelets taglib functions 534
Facelets pitfalls 536
AJAX and <ui:repeat> 536
Exemplifying <c:if> versus <ui:fragment> 537
Exemplifying <c:forEach> versus <ui:repeat> 538
Summary 539
Appendix: The JSF Life Cycle 541
Index 543

[ vii ]
Preface
This book will cover all the important aspects (Big Ticket features) involved in
developing JSF 2.2 applications. It provides clear instructions for getting the most
out of JSF 2.2 and offers many exercises (more than 300 complete applications) to
build impressive JSF-based web applications.

We start off with a chapter about Expression Language (EL) and cover the
most important aspects of EL 2.2 and EL 3.0. We continue with a comprehensive
dissertation about communication in JSF, followed by an exciting chapter about
JSF 2.2 scopes. At this point, we bring into discussion most of the JSF artifacts and
configurations. Further, we start a suite of very interesting topics, such as HTML5
and AJAX. After that we dissect the JSF view state concept and learn how to deal
with this delicate JSF topic. Furthermore, we will discuss in detail about custom
components and composite components. After this, we will talk about library
contracts (themes) of JSF 2.2 resources. Finally, the last chapter will fortify your
knowledge about JSF 2.2 Facelets.

What this book covers


Chapter 1, Dynamic Access to JSF Application Data through Expression Language (EL 3.0),
covers the main aspects of Expression Language (EL). We will cover EL 2.2 and EL
3.0, including new operators, lambda expressions, and collection object support.

Chapter 2, Communication in JSF, represents a dissection of JSF mechanisms used


for ensuring communication between JSF artifacts. Therefore, we will cover context
parameters, request parameters, JSF 2.2 actions on GET requests (view actions),
and more.
Preface

Chapter 3, JSF Scopes – Lifespan and Use in Managed Beans Communication, teaches you
to distinguish between the bad and good practices of using JSF and CDI scopes. We
will discuss JSF scopes versus CDI scopes, request, session, view scope (including the
new JSF 2.2 view scope), application, conversation scope, JSF 2.2 flow scope in detail
(Big Ticket feature), and more.

Chapter 4, JSF Configurations Using XML Files and Annotations – Part 1, depicts the
JSF artifact's configuration aspects in a learning-by-example fashion. Configuring
JSF artifacts in the faces-config.xml file is pretty straightforward and boring,
but if we take each artifact and exploit its potential in several use cases, then things
become much more interesting.

Chapter 5, JSF Configurations Using XML Files and Annotations – Part 2, acts as a
continuation of the previous chapter. Here, we will discuss configuring resource
handlers (JSF 2.2's new javax.faces.WEBAPP_RESOURCES_DIRECTORY context
parameter), configuring flash (JSF 2.2 FlashFactory, FlashWrapper, and flash
system events), JSF 2.2 Window ID API, the injection mechanism (which, starting
with JSF 2.2, is possible in most JSF artifacts), and more.

Chapter 6, Working with Tabular Data, pays tribute to the <h:dataTable> tag.
Here, we will focus on the JSF 2.2 CollectionDataModel API (which supports the
Collection interface in UIData). Moreover, we will learn about table pagination,
deleting/editing/updating table rows, filtering, and styling JSF tables.

Chapter 7, JSF and AJAX, exploits the JSF 2.2 delay attribute for queue control of
AJAX requests. It discusses how to reset value attributes using JSF 2.2 (input fields
can be updated with AJAX after a validation error), AJAX and JSF 2.2 flow scope,
how to customize AJAX script, and more. This is a classic chapter in almost any
JSF book.

Chapter 8, JSF 2.2 – HTML5 and Upload, divides the topic into two parts. The first part
is entirely dedicated to the Big Ticket feature, HTML5, and JSF 2.2 (pass-through
attributes and elements). The second part is dedicated to JSF 2.2's new upload
component, <h:inputFile>.

Chapter 9, JSF State Management, provides a detailed dissertation about the JSF view
state. The headings of this chapter will refer to JSF's saving view state (including
JSF 2.2 case insensitivity for state saving method and standardized server state
serialization) and JSF 2.2 stateless view (Big Ticket feature).

Chapter 10, JSF Custom Components, is another example of a classic chapter in


any JSF book. Obviously, the main topics are meant to shape the custom and
composite components creation. We will focus on developing several kinds of
components based on the new JSF 2.2 approach (Facelet's component tag can be
declared via annotation).

[2]
Preface

Chapter 11, JSF 2.2 Resource Library Contracts – Themes, dedicates itself to the new
JSF 2.2 Resource Library Contracts feature (Big Ticket feature). You will learn how
to work with contracts, style JSF tables and UI components using contracts, style
contracts across different kind of devices, and more.

Chapter 12, Facelets Templating, depicts the viral aspects of Facelets templating.
We will focus on the declarative and programmatical aspects of Facelets.

Appendix, The JSF Life Cycle, covers a diagram of the different JSF phases.

What you need for this book


In order to run the applications in this book, you will need the following
software applications:

• NetBeans IDE (preferred version is 8.0, or later)


• GlassFish 4.0
• JSF Mojarra 2.2.6 (preferred) / MyFaces 2.2.2

Who this book is for


This book is a perfect symbiosis between JSF 2.0 and 2.2. It is dedicated to JSF
developers who have previous experience and want to upgrade their knowledge
to the new JSF 2.2. By fortifying your knowledge on JSF 2.0 and adding the power
of JSF 2.2, you will soon become a JSF expert.

Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as
follows: "For example, in the following example, you call a method named
firstLambdaAction—the lambda expression is invoked from this method."

A block of code is set as follows:


<ui:repeat value="#{get_sublist(myList, from, to)}" var="t">
#{t}
</ui:repeat>

[3]
Preface

When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
<h:dataTable value="#{playersBean.dataArrayList}"
binding="#{table}" var="t">

New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "When
the Login button is clicked, JSF will call the playerLogin method."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for
us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to feedback@packtpub.com,


and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.

Downloading the example code


You can download the example code files for all Packt books you have purchased
from your account at http://www.packtpub.com. If you purchased this book
elsewhere, you can visit http://www.packtpub.com/support and register to
have the files e-mailed directly to you.

[4]
Preface

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you would report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the errata submission form link,
and entering the details of your errata. Once your errata are verified, your submission
will be accepted and the errata will be uploaded on our website, or added to any list of
existing errata, under the Errata section of that title. Any existing errata can be viewed
by selecting your title from http://www.packtpub.com/support.

Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.

Please contact us at copyright@packtpub.com with a link to the suspected


pirated material.

We appreciate your help in protecting our authors, and our ability to bring you
valuable content.

Questions
You can contact us at questions@packtpub.com if you are having a problem with
any aspect of the book, and we will do our best to address it.

[5]
Dynamic Access to
JSF Application Data
through Expression
Language (EL 3.0)
Java Expression Language (EL) is a compact and powerful mechanism that enables
dynamic communication in JSP and JSF-based applications (including development
frameworks based on JSF such as PrimeFaces, ICEfaces, and RichFaces); we embed
expressions in the presentation layer to communicate with the application logic
layer. EL provides bidirectional communication, which means that we can expose
application logic data to the user, but we also can submit user data to be processes.
Generically speaking, EL can be used to populate HTTP requests with user data,
to extract and expose data from HTTP responses, to update HTML DOM, to
conditionally process data, and much more.

Commonly, EL expressions will be present in JSP and JSF pages, but


they can also appear outside, in faces-config.xml, for example.

In this chapter, you will see how to use EL in web pages to communicate with
managed beans, which is the most common case in JSF applications. We will
cover the following topics:

• EL syntax, operators, and reserved words


• EL immediate and deferred evaluation
Dynamic Access to JSF Application Data through Expression Language (EL 3.0)

• EL value and method expressions


• The conditional text in JSF
• Write a custom EL resolver

EL syntax
In this section, you can see an overview of the main aspects of EL 2.2 and 3.0 syntax.
EL supports a handful of operators and reserved words. Each of these are quickly
described in the following section (more details are in the EL specification document
(http://download.oracle.com/otndocs/jcp/el-3_0-fr-eval-spec/index.html)).

EL operators
EL supports the following categories of operators—arithmetic, relational, logical,
conditional, empty and added starting with EL 3.0, string concatenation, assignment
and semicolon operators:

Textuals Description Symbols


A+B Addition +
A-B Subtraction -
A*B Multiplication *
A {div, /} B Arithmetic operator division /, div
A {mod, %} B Arithmetic operator modulo %, mod
A {and, &&} B Logical AND &&, and
A {or, ||} B Logical OR ||, or
{not, !} A Logical opposite !, not
A {lt, <} B Relational less than <, lt
A {gt, >} B Relational greater than >, gt
A {le, <=} B Relational less than or equal to <=, le
A {ge, >=} B Relational greater than or equal to >=, ge
A {eq, ==} B Equal to ==, eq
A {ne, !=} B Not equal to !=, ne
A = B Assignment (EL 3.0) =
A; B Semicolon (EL 3.0) ;
A += B String concatenation (EL 3.0) +=
A -> B Lambda expression (EL 3.0) ->

[8]
Chapter 1

Textuals Description Symbols


empty A Determine whether a value is null or empty
A ? B : C Evaluates B or C, depending on the result of the evaluation ?:
of A. Known as the ternary operator.
Used when writing EL expressions .
Used when writing EL expressions []

EL precedence of operators
Conforming to EL specification, the precedence of operators from the highest to
lowest, left to right is as follows:

• [].
• () (used to change the precedence of operators)
• - (unary) not ! empty
• * / div % mod
• + - (binary)
• +=
• < > <= >= lt gt le ge
• == != eq ne
• && and
• || or
• ?:
• -> (lambda expression)
• =
• ;

EL reserved words
EL defines the following reserved words:

• and, or, not, eq, ne, lt, gt, le, ge, true (Boolean literal), false
(Boolean literal), null, instanceof (a Java keyword to do a class
comparison between objects), empty, div, and mod

[9]
Dynamic Access to JSF Application Data through Expression Language (EL 3.0)

EL immediate and deferred evaluation


EL evaluates expressions as immediate or deferred.

Immediate evaluation returns the result as soon as the page is first rendered. These
kinds of expressions are read-only value expressions and they can be present only in
tags that accept runtime expressions. They are easy to recognize after the ${} notation.
Usually, they are used for arithmetic and logical operations in JSP pages.

Deferred evaluation can return the result at different phases of a page's life cycle
depending on the technology that is using the expression. JSF can evaluate the
expression at different phases of the life cycle (for example, during the rendering
and postback phase), depending on how the expression is being used in the page.
These kind of expressions can be value and method expressions, and they are
marked by the #{} notation.

In Facelets, ${} and #{} act the same.

EL value expressions
Value expressions are probably used the most, and they refer to objects and their
properties and attributes. Such expressions are dynamically used to evaluate results
or set bean properties at runtime. Through value expressions, you can easily access
JavaBeans components, collections, and Java SE enumerated types. Moreover, EL
provides a set of implicit objects that can be used to get attributes from different
scopes and parameter values. Furthermore, you will see how EL deals with each of
these objects.

Value expressions that can read data, but cannot write it are known
as rvalue (${} expressions are always rvalue), while those that can
read and write data are known as lvalue (#{} expressions can be
rvalue and/or lvalue).

Referencing a managed bean


Referencing a managed bean is not exactly a useful example, but it is a good point to
start. Most commonly, your managed bean will look like the following code (in this
case, the bean's class name is PlayersBean):
@ManagedBean
//some scope

[ 10 ]
Chapter 1

public class PlayersBean{


...
}

Or, in the CDI version, your managed bean will be as follows:


@Named
//some scope
public class PlayersBean{
...
}

Or, with an explicit name, your managed bean will be as follows:


@ManagedBean(name = "myPlayersBean")
//some scope
public class PlayersBean{
...
}

@Named(value = "myPlayersBean")
//some scope
public class PlayersBean{
...
}

Now, for the first two examples, EL refers to the PlayersBean managed bean, like
this—the name is obtained from taking the unqualified class name portion of the
fully qualified class name and converting the first character to lowercase as follows:
#{playersBean}

In addition, for the next two examples, EL uses the explicit name as follows:
#{myPlayersBean}

You should use CDI beans whenever possible since they are
more flexible than JSF managed beans, and because annotations
from javax.faces.bean will be deprecated in a future JSF
version. Therefore, the CDI ones are recommended.

[ 11 ]
Dynamic Access to JSF Application Data through Expression Language (EL 3.0)

When the referenced managed bean cannot be found in any scope, a null value will
be returned.

Downloading the example code


You can download the example code files for all Packt books you have
purchased from your account at http://www.packtpub.com. If you
purchased this book elsewhere, you can visit http://www.packtpub.
com/support and register to have the files e-mailed directly to you.

Referencing a managed bean's properties


As is commonly known, managed beans usually contain private fields, which are
accessible through getter and setter methods as bean properties, and some public
methods that exploits these properties to serve different logic tasks.

EL expressions that can access these properties contain the dot or square brackets
notation, []. For example, let's suppose that the PlayersBean managed bean
contains two fields defined like the following lines:
private String playerName = "Rafael";
private String playerSurname = "Nadal";

EL can access these fields through their getter methods; therefore, you need to define
them as shown in the following code:
public String getPlayerName() {
return playerName;
}
public String getPlayerSurname() {
return playerSurname;
}

Now, an expression that accesses the playerName property can use the dot
notation (.) to refer it, as shown in the following line of code:
#{playersBean.playerName}

Alternatively, this expression can use the square brackets notation, [], as shown in
the following line of code:
#{playersBean['playerName']}

[ 12 ]
Random documents with unrelated
content Scribd suggests to you:
Atlas. Here lies such a gentleman, sir, whose
clothes (were they not greasy) would bespeak
him so.
Light. Then I pray, sir, when your leisure shall
permit, that you would vouchsafe to help me to
the speech of him.
Atlas. We must first crave your oath, sir, that
you come not with intent to molest, perturb, or
endanger him; for he is a gentleman, whom it
hath pleased fortune to make her tennis-ball of,
and therefore subject to be struck by every fool
into hazard.
Light. In that I commend thy care of him, for
which friendship here's a slight reward; tell him
a countryman of his, one Lightfoot, is here,
and[364] [he] will not any way despair of his
safety.
Atlas. With all respect, sir; pray, command my
house.
[Exit Atlas.

Light. So now I shall have a sight of my cousin


gallant: he that hath consumed £800 a year in
as few years as he hath ears on his head: he
that was wont never to be found without three
or four pair of red breeches running before his
horse or coach: he that at a meal hath had
more several kinds than, I think, the ark
contained: he that was admired by niters[365]
for his robes of gallantry, and was indeed all
that an elder brother might be—prodigal; yet
he, whose unthriftiness kept many a house, is
now glad to keep house in a house that keeps
him, the poor tenant of a porter. And see his
appearance! I'll seem strange to him.
Enter Haddit, in poor array.
Had. Cousin Lightfoot, how dost? welcome to
the city.
Light. Who calls me cousin? where's my cousin
Haddit? he's surely putting on some rich apparel
for me to see him in. I ha' been thinking all the
way I came up, how much his company will
credit me.
Had. My name is Haddit, sir, and your kinsman,
if parents may be trusted; and therefore you
may please to know me better when you see
me next.
Light. I prythee, fellow, stay: is it possible thou
shouldst be he? why, he was the generous
spark of men's admiration.

Had. I am that spark, sir, though now raked


up in ashes;
Yet when it pleaseth fortune's chaps to blow
Some gentler gale upon me, I may then
From forth of embers rise and shine again.

Light. O, by your versifying I know you now, sir:


how dost? I knew thee not at first, thou'rt very
much altered.
Had. Faith, and so I am, exceeding much since
you saw me last—about £800 a year; but let it
pass, for passage[366] carried away the most
part of it: a plague of fortune.
Light. Thou'st more need to pray to Fortune
than curse her: she may be kind to thee when
thou art penitent: but that, I fear, will be never.
Had. O, no, if she be a woman, she'll ever love
those that hate her. But, cousin, thou art thy
father's first-born; help me but to some means,
and I'll redeem my mortgag'd lands, with a
wench to boot.
Light. As how, I pray thee?
Had. Marry thus: Hog the usurer hath one only
daughter.
Light. Is his name Hog? It fits him exceeding
well; for as a hog in his lifetime is always
devouring, and never commodious in aught till
his death; even so is he, whose goods at that
time may be put to many good uses.
Had. And so I hope they shall before his death.
This daughter of his did, and I think doth, love
me; but I, then thinking myself worthy of an
empress, gave but slight respect unto her
favour, for that her parentage seemed not to
equal my high thoughts, puffed up——
Light. With tobacco, surely.
Had. No; but with as bad a weed—vainglory.
Light. And you could now be content to put
your lofty spirits into the lowest pit of her
favour. Why, what means will serve, man?
'Sfoot, if all I have will repair thy fortune, it shall
fly at thy command.
Had. Thanks, good coz, the means shall not be
great, only that I may first be clad in a
generous outside, for that is the chief attraction
that draws female affection. Good parts,
without habiliments of gallantry, are no more
set by in these times than a good leg in a
woollen stocking. No, 'tis a glistering presence
and audacity brings women into fool's felicity.
Light. You've a good confidence, coz; but what
do ye think your brave outside shall effect?
Had. That being had, we'll to the usurer, where
you shall offer some slight piece of land to
mortgage, and if you do it to bring ourselves
into cash, it shall be ne'er the farther from you,
for here's a project will not be frustrate of this
purpose.
Light. That shall be shortly tried. I'll instantly go
seek for a habit for thee, and that of the richest
too; that which shall not be subject to the scoff
of any gallant, though to the accomplishing
thereof all my means go. Alas! what's a man
unless he wear good clothes?
[Exit Lightfoot.

Had. Good speed attend my suit! Here's a


never-seen nephew kind in distress; this gives
me more cause of admiration than the loss of
thirty-five settings together at passage. Ay,
when 'tis performed—but words and deeds are
now more different than puritans and players.
Enter Atlas.
Atlas. Here's the player would speak with you.
Had. About the jig I promised him. My pen and
ink! I prythee, let him in, there may be some
cash rhymed out of him.
Enter Player.
Player. The Muses assist you, sir: what, at your
study so early?
Had. O, chiefly now, sir: for Aurora Musis amica.
Player. Indeed, I understand not Latin, sir.
Had. You must then pardon me, good Master
Change-coat; for I protest unto you, it is so
much my often converse that, if there be none
but women in my company, yet cannot I forbear
it.
Player. That shows your more learning, sir; but,
I pray you, is that small matter done I
entreated for?
Had. A small matter! you'll find it worth Meg of
Westminster,[367] although it be but a bare jig.
Player. O Lord, sir, I would it had but half the
taste of garlic.[368]
Had. Garlic stinks to this; if it prove that you
have not more whores than e'er garlic had, say
I am a boaster of my own works, disgrace me
on the open stage, and bob me off with ne'er a
penny.
Player. O Lord, sir, far be it from us to debar any
worthy writer of his merit; but I pray you, sir,
what is the title you bestow upon it?
Had. Marry, that which is full as forcible as
garlic: the name of it is, Who buys my four
ropes of hard onions? by which four ropes is
meant, four several kind of livers; by the
onions, hangers-on—as at some convenient
time I will more particularly inform you in so
rare a hidden and obscure mystery.
Player. I pray, let me see the beginning of it. I
hope you have made no dark sentence in't; for,
I'll assure you, our audience commonly are very
simple, idle-headed[369] people, and if they
should hear what they understand not, they
would quite forsake our house.
Had. O, ne'er fear it; for what I have writ is both
witty to the wise, and pleasing to the ignorant:
for you shall have those laugh at it far more
heartily that understand it not, than those that
do.
Player. Methinks the end of this stave is a foot
too long.
Had. O no, sing it but in tune, and I dare
warrant you.

Player. Why, hear ye.


[He sings.

And you that delight in trulls and minions,


Come buy my four ropes of hard St
Thomas's onions.[370]

Look ye there, St Thomas might very well


have been left out; besides, hard
should have come next the onions.
Had. Fie! no; the dismembering of a rhyme to
bring in reason shows the more efficacy in the
writer.
Player. Well, as you please; I pray you, sir, what
will the gratuity be? I would content you as
near hand as I could.
Had. So I believe. [Aside.] Why, Master Change-
coat, I do not suppose we shall differ many
pounds; pray, make your offer: if you give me
too much, I will, most doctor-of-physic-like,
restore.
Player. You say well; look you, sir, there's a
brace of angels, besides much drink of free-
cost, if it be liked.
Had. How, Master Change-coat! a brace of
angels, besides much drink of free-cost, if it be
liked! I fear you have learned it by heart; if you
have powdered up my plot in your sconce, you
may home, sir, and instruct your poet over a pot
of ale the whole method on't. But if you do so
juggle, look to't. Shrove-Tuesday[371] is at hand,
and I have some acquaintance with bricklayers
and plasterers.
Player. Nay, I pray, sir, be not angry; for as I am
a true stage-trotter, I mean honestly; and look
ye, more for your love than otherwise, I give
you a brace more.
Had. Well, good words do much; I cannot now
be angry with you, but see henceforward you
do like him that would please a new-married
wife, show your most at first, lest some other
come between you and your desires; for I
protest, had you not suddenly shown your
good-nature, another should have had it,
though it had been for nothing.
Player. Troth, I'm sorry I gave you such cause of
impatiency; but you shall see hereafter, if your
invention take, I will not stand off for a brace
more or less, desiring I may see your works
before another.
Had. Nay, before all others; and shortly expect a
notable piece of matter, such a jig whose tune,
with the natural whistle of a carman, shall be
more ravishing to the ears of shopkeepers than
a whole consort of barbers at midnight.
Player. I am your man for't; I pray you,
command all the kindness belongs to my
function, as a box for your friend at a new play,
although I procure the hate of all my company.
Had. No, I'll pay for it rather; that may breed a
mutiny in your whole house.
Player. I care not, I ha' played a king's part any
time these ten years; and if I cannot command
such a matter, 'twere poor, faith.
Had. Well, Master Change-coat, you shall now
leave me, for I'll to my study; the morning
hours are precious, and my Muse meditates
most upon an empty stomach.
Player. I pray, sir, when this new invention is
produced, let me not be forgotten.
Had. I'll sooner forget to be a jig-maker. [Exit
Player.] So, here's four angels I little dreamt of.
Nay, and there be money to be gotten by
foolery, I hope fortune will not see me want.
Atlas, Atlas!
Enter Atlas.
What, was my country coz here since?
Atlas. Why, did he promise to come again,
seeing how the case stood wi' ye?
Had. Yea, and to advance my downfallen
fortunes, Atlas.
Atlas. But ye are not sure he meant it ye, when
he spake it.
Had. No, nor is it in man to conjecture rightly
the thought by the tongue.
Atlas. Why, then, I'll believe it when I see it. If
you had been in prosperity when he had
promised you this kindness——
Had. I had not needed it.
Atlas. But being now you do, I fear you must go
without it.
Had. If I do, Atlas, be it so: I'll e'en go write this
rhyme over my bed's head—

Undone by folly; fortune, lend me more.


Canst thou, and wilt not? pox on such a
whore!

and so I'll set up my rest. But see, Atlas, here's


a little of that that damns lawyers; take it in
part of a further recompense.
Atlas. No, pray keep it; I am conceited of your
better fortunes, and therefore will stay out that
expectation.
Had. Why, if you will, you may; but the
surmounting of my fortunes is as much to be
doubted as he whose estate lies in the lottery—
desperate.
Atlas. But ne'er despair. 'Sfoot, why should not
you live as well as a thousand others that wear
change of taffata, whose means were never
anything?
Had. Yes, cheating, theft and panderising, or,
maybe, flattery: I have maintained some of
them myself. But come, hast aught to
breakfast?
Atlas. Yes, there's the fag-end of a leg of
mutton.
Had. There cannot be a sweeter dish; it has cost
money the dressing.
Atlas. At the barber's, you mean.
[Exeunt.

Enter Albert solus.

Alb. This is the green, and this the chamber-


window:
And see, the appointed light stands in the
casement,
The ladder of ropes set orderly; yet he
That should ascend, slow in his haste, is not
As yet come hither.
Were't any friend that lives but Carracus,
I'd try the bliss which this fine time presents.
Appoint to carry hence so rare an heir,
And be so slack! 'sfoot, it doth move my
patience.
Would any man, that is not void of sense,
Not have watch'd night by night for such a
prize?
Her beauty's so attractive that, by heav'n,
My heart half grants to do my friend a wrong.
Forego these thoughts; for,[372] Albert, be
not slave
To thy affection; do not falsify
Thy faith to him, whose only friendship's
worth
A world of women. He is such a one,
Thou canst not live without his good:
A' is and was ever as thine own heart's blood.
[Maria beckons him in the window.

'Sfoot, see, she beckons me for Carracus:


Shall my base purity cause me neglect
This present happiness? I will obtain it,
Spite of my timorous conscience. I am in
person,
Habit, and all so like to Carracus,
It may be acted, and ne'er call'd in question.

Maria calls. Hist! Carracus, ascend:


All is as clear as in our hearts we wish'd.

Alb. Nay, if I go not now, I might be gelded, i'


faith!
[Albert ascends; and, being on the top of the
ladder, puts out the candle.
Mar. O love, why do you so?

Alb. I heard the steps of some coming this


way.
Did you not hear Albert pass by as yet?

Mar. [No;] nor any creature pass this way this


hour.

Alb. Then he intends, just at the break of day,


To lend his trusty help to our departure.
'Tis yet two hours' time thither, till when, let's
rest.
For that our speedy flight will not yield any.

Mar. But I fear,


We, possessing of each other's presence,
Shall overslip the time. Will your friend call?

Alb. Just at the instant: fear not of his care.

Mar. Come then, dear Carracus, thou now


shalt rest
Upon that bed, where fancy oft hath thought
thee;
Which kindness until now I ne'er did grant
thee,
Nor would I now, but that thy loyal faith
I have so often tried; even now
Seeing thee come to that most honour'd end,
Through all the dangers which black night
presents,
For to convey me hence and marry me.

Alb. If I do not do so, then hate me ever.


Mar. I do believe thee, and will hate thee never.
[Exeunt.

Enter Carracus.

How pleasing are the steps we lovers make,


When in the paths of our content we pace,
To meet our longings! What happiness it is
For man to love! But O, what greater bliss
To love and be belov'd! O, what one virtue
E'er reign'd in me, that I should be enrich'd
With all earth's good at once! I have a friend,
Selected by the heavens as a gift
To make me happy, whilst I live on earth:
A man so rare of goodness, firm of faith,
That earth's content must vanish in his death.
Then for my love and mistress of my soul,
A maid of rich endowments, beautifi'd[373]
With all the virtues nature could bestow
Upon mortality, who this happy night
Will make me gainer of her heav'nly self.
And see, how suddenly I have attain'd
To the abode of my desired wishes!
This is the green; how dark the night
appears!
I cannot hear the tread of my true friend.
Albert! hist, Albert!—he's not come as yet,
Nor is th' appointed light set in the window.
What, if I call Maria? it may be
She fear'd to set a light, and only hark'neth
To hear my steps; and yet I dare not call,
Lest I betray myself, and that my voice,
Thinking to enter in the ears of her,
Be of some other heard: no, I will stay,
Until the coming of my dear friend Albert.
But now think, Carracus, what the end will be
Of this thou dost determine: thou art come
Hither to rob a father of that wealth,
That solely lengthens his now drooping years,
His virtuous daughter, and all of that sex left,
To make him happy in his aged days:
The loss of her may cause him to despair,
Transport his near-decaying sense to frenzy,
Or to some such abhorred inconveniency,
Whereto frail age is subject. I do too ill in
this,
And must not think, but that a father's plaint
Will move the heavens to pour forth misery
Upon the head of disobediency.
Yet reason tells us, parents are o'erseen,
When with too strict a rein they do hold in
Their child's affections, and control that love,
Which the high pow'rs divine inspire them
with,
When in their shallowest judgments they may
know,
Affection cross'd brings misery and woe.
But whilst I run contemplating on this,
I softly pace to my desired bliss.
I'll go into the next field, where my friend
Told me the horses were in readiness.
[Exit.

Albert descending from Maria.


Maria. But do not stay. What, if you find not
Albert?
Alb. I'll then return alone to fetch you hence.

Maria. If you should now deceive me, having


gain'd
What you men seek for——
Alb. Sooner I'll deceive
My soul—and so, I fear, I have.
[Aside.

Maria. At your first call, I will descend.

Alb. Till when this touch of lips be the true


pledge
Of Carracus' constant true devoted love.

Maria. Be sure you stay not long; farewell;


I cannot lend an ear to hear you part.
[Exit Maria.

Alb. But you did lend a hand unto my


entrance.
[He descends.

How have I wrong'd my friend, my faithful


friend!
Robb'd him of what's more precious than his
blood,
His earthly heaven, the unspotted honour
Of his soul-joying mistress! the fruition of
whose bed
I yet am warm of; whilst dear Carracus
Wanders this cold night through th'
unshelt'ring field,
Seeking me, treacherous man; yet no man
neither,
Though in an outward show of such
appearance,
But am a devil indeed; for so this deed
Of wronged love and friendship rightly makes
me.
I may compare my friend to one that's sick,
Who, lying on his deathbed, calls to him
His dearest-thought friend, and bids him go
To some rare-gifted man, that can restore
His former health: this his friend sadly hears,
And vows with protestations to fulfil
His wish'd desires with his best performance;
But then, no sooner seeing that the death
Of his sick friend would add to him some
gain,
Goes not to seek a remedy to save,
But, like a wretch, hies[374] him to dig his
grave;
As I have done for virtuous Carracus.
Yet, Albert, be not reasonless, to endanger
What thou may'st yet secure; who can detect
The crime of thy licentious appetite?—
I hear one's pace! 'tis surely Carracus.
Enter Carracus.

Car. Not find my friend! sure, some malignant


planet
Rules o'er this night, and, envying the
content
Which I in thought possess, debars me thus
From what is more than happy, the lov'd
presence
Of a dear friend and love.

Alb. 'Tis wronged Carracus by Albert's


baseness:
I have no power now to reveal myself.

Car. The horses stand at the appointed place,


And night's dark coverture makes firm our
safety.
My friend is surely fall'n into a slumber
On some bank hereabouts; I will call him.
Friend Albert, Albert!
Alb. Whate'er you are that call, you know my
name.
Car. Ay, and thy heart, dear friend.

Alb. O Carracus, you are a slow-pac'd lover!


Your credit had been touch'd, had I not been.

Car. As how, I prythee, Albert?

Alb. Why, I excus'd you to the fair Maria;


Who would have thought you else a slack
performer.
For coming first under her chamber-window,
She heard me tread, and call'd upon your
name;
To which I answer'd with a tongue like yours,
And told her I would go to seek for Albert,
And straight return.

Car. Whom I have found; thanks to thy faith


and heav'n.
But had not she a light when you came first?

Alb. Yes, but hearing of some company,


She at my warning was forc'd to put it out.
And had I been so too, you and I too
Had still been happy.
[Aside.

Car. See, we are now come to the chamber-


window.
Alb. Then you must call, for so I said I would.
Car. Maria.

Maria. My Carracus, are you so soon return'd?


I see you'll keep your promise.

Car. Who would not do so, having pass'd it


thee,
Cannot be fram'd of aught but treachery:
Fairest, descend, that by our hence departing
We may make firm the bliss of our content.

Maria. Is your friend Albert with you?


Alb. Yes, and your servant, honoured lady.

Maria. Hold me from falling, Carracus.


[She descends.

Car. I will do now so, but not at other times.

Maria. You are merry, sir:


But what d' y' intend with this your scaling-
ladder,
To leave it thus, or put it forth of sight?

Car. Faith, 'tis no great matter which:


Yet we will take it hence, that it may breed
Many confus'd opinions in the house
Of your escape. Here, Albert, you shall bear
it;
It may be you may chance to practise that
way;
Which when you do, may your attempts so
prove,
As mine have done—most fortunate in love.
Alb. May you continue ever so!
But it's time now to make some haste to
horse;
Night soon will vanish. O, that it had power
For ever to exclude day from our eyes,
For my looks, then, will show my villany.
[Aside.

Car. Come, fair Maria, the troubles of this


night
Are as forerunners to ensuing pleasures.
And, noble friend, although now Carracus
Seems, in the gaining of this beauteous prize,
To keep from you so much of his lov'd
treasure,
Which ought not to be mixed; yet this heart
Shall so far strive in your wish'd happiness,
That if the loss and ruin of itself
Can but avail your good——

Alb. O friend! no more; come, you are slow in


haste;
Friendship ought never be discuss'd in words,
Till all her deeds be finish'd. Who, looking in
a book,
And reads but some part only, cannot judge
What praise the whole deserves, because his
knowledge
Is grounded but on part. As thine, friend, is
Ignorant of that black mischief I have done
thee.
[Aside.

Mar. Carracus, I am weary; are the horses


far?
Car. No, fairest, we are now even at them:
Come, do you follow, Albert?

Alb. Yes, I do follow; would I had done so


ever,
And ne'er had gone before.
[Aside. Exeunt.
ACTUS SECUNDUS.
Enter Hog the usurer; with Peter Servitude,
trussing his points.
Hog. What, hath not my young Lord Wealthy
been here this morning?
P. Ser. No, in very deed, sir; he is a towardly
young gentleman; shall he have my young
mistress, your daughter, I pray you, sir?
Hog. Ay, that he shall, Peter; she cannot be
matched to greater honour and riches in all this
country: yet the peevish girl makes coy of it,
she had rather affect a prodigal; as there was
Haddit, one that by this time cannot be
otherwise than hanged, or in some worse
estate; yet she would have had him: but I
praise my stars she went without him, though I
did not without his lands. 'Twas a rare
mortgage, Peter.
P. Ser. As e'er came in parchment: but see, here
comes my young lord.
Enter Young Lord Wealthy.
Y. Lord W. Morrow, father Hog; I come to tell
you strange news; my sister is stol'n away to-
night, 'tis thought by necromancy. What
necromancy is, I leave to the readers of the
"Seven Champions of Christendom."[375]
Hog. But is it possible your sister should be
stolen? sure, some of the household servants
were confederates in't.
Y. Lord W. Faith, I think they would have
confessed, then; for I am sure my lord and
father hath put them all to the bastinado twice
this morning already: not a waiting-woman, but
has been stowed, i' faith.
P. Ser. Trust me, he says well for the most part.
Hog. Then, my lord, your father is far impatient.
Y. Lord W. Impatient! I ha' seen the picture of
Hector[375] in a haberdasher's shop not look
half so furious; he appears more terrible than
wildfire at a play. But, father Hog, when is the
time your daughter and I shall to this wedlock-
drudgery?
Hog. Troth, my lord, when you please; she's at
your disposure, and I rest much thankful that
your lordship will so highly honour me. She
shall have a good portion, my lord, though
nothing in respect of your large revenues. Call
her in, Peter; tell her my most respected Lord
Wealthy is here, to whose presence I will now
commit her [Exit Peter]; and I pray you, my
lord, prosecute the gain of her affection with
the best affecting words you may, and so I bid
good morrow to your lordship.
[Exit Hog.

Y. Lord W. Morrow,[377] father Hog. To


prosecute the gain of her affection with the best
affecting words; as I am a lord, a most rare
phrase! well, I perceive age is not altogether
ignorant, though many an old justice is so.
Enter Peter Servitude.
How now, Peter, is thy young mistress up yet?
P. Ser. Yes, indeed, she's an early stirrer; and I
doubt not hereafter but that your lordship may
say, she's abroad before you can rise.
Y. Lord W. Faith, and so she may, for 'tis long
ere I can get up, when I go foxed to bed. But,
Peter, has she no other suitors besides myself?
P. Ser. No, and it like your lordship; nor is it fit
she should.
Y. Lord W. Not fit she should? I tell thee, Peter, I
would give away as much as some knights are
worth, and that's not much, only to wipe the
noses of some dozen or two of gallants, and to
see how pitifully those parcels of men's flesh
would look, when I had caught the bird which
they had beaten the bush for.
P. Ser. Indeed, your lordship's conquest would
have seemed the greater.
Y. Lord W. Foot, as I am a lord, it angers me to
the guts, that nobody hath been about her.
P. Ser. For anything I know, your lordship may
go without her.
Y. Lord W. An' I could have enjoyed her to some
pale-faced lover's distraction, or been envied for
my happiness, it had been somewhat.
Enter Rebecca, Hog's daughter.
But see where she comes! I knew she had not
power enough to stay another sending for. O
lords! what are we? our names enforce beauty
to fly, being sent for. [Aside.] Morrow, pretty
Beck: how dost?
Reb. I rather should enquire your lordship's
health, seeing you up at such an early hour.
Was it the toothache, or else fleas disturbed
you?
Y. Lord W. Do you think I am subject to such
common infirmities? Nay, were I diseased, I'd
scorn but to be diseased like a lord, i' faith. But
I can tell you news, your fellow virgin-hole
player,[378] my sister, is stolen away to-night.
Reb. In truth. I am glad on't; she is now free
from the jealous eye of a father. Do not ye
suspect, my lord, who it should be that has
carried her away?
Y. Lord W. No, nor care not; as she brews, so let
her bake; so said the ancient proverb. But, lady,
mine that shall be, your father hath wished[379]
me to appoint the day with you.
Reb. What day, my lord?
Y. Lord W. Why, of marriage; or as the learned
historiographer[380] writes, Hymen's holidays,
or nuptial ceremonious rites.
Reb. Why, when would you appoint that, my
lord?
Y. Lord W. Why, let me see, I think the tailor
may despatch all our vestures in a week:
therefore, it shall be directly this day se'ennight.
P. Ser. God give you joy!
Reb. Of what, I pray, you impudence? This
fellow will go near to take his oath that he hath
seen us plight faiths together; my father keeps
him for no other cause than to outswear the
truth. My lord, not to hold you any longer in a
fool's paradise, nor to blind you with the hopes
I never intend to accomplish, know, I neither
do, can, or will love you.
Y. Lord W. How! not love a lord? O indiscreet
young woman! Indeed, your father told me how
unripe I should find you: but all's one, unripe
fruit will ask more shaking before they fall than
those that are; and my conquest will seem the
greater still.
[Aside.]

P. Ser. Afore God, he is a most unanswerable


lord, and holds her to't, i' faith.
Y. Lord W. Nay, you could not have pleased me
better, than seeing you so invincible, and of
such difficult attaining to. I would not give a pin
for the society of a female that should seem
willing; but give me a wench that hath
disdainful looks;

For 'tis denial whets an appetite,


When proffer'd service doth allay delight.

Reb. The fool's well-read in vice. [Aside.] My


lord, I hope you hereafter will no farther
insinuate in the course of your affections; and,
for the better withdrawing from them, you may
please to know, I have irrevocably decreed
never to marry.
Y. Lord W. Never to marry! Peter, I pray bear
witness of her words that, when I have attained
her, it may add to my fame and conquest.
Reb. Yes, indeed, an't like your lordship.
Y. Lord W. Nay, ye must think, Beck, I know
how to woo; ye shall find no bashful university-
man of me.
Reb. Indeed, I think y' had ne'er that bringing
up. Did you ever study, my lord?
Y. Lord W. Yes, faith, that I have, and, the last
week too, three days and a night together.
Reb. About what, I pray?
Y. Lord W. Only to find out why a woman, going
on the right side of her husband in the daytime,
should lie on his left side at night; and, as I am
a lord, I never knew the meaning on't till
yesterday. Malapert, my father's butler, being a
witty jackanapes, told me why it was.
Reb. By'r Lady, my lord, 'twas a shrewd study,
and I fear hath altered the property of your
good parts; for, I'll assure you, I loved you a
fortnight ago far better.
Y. Lord W. Nay, 'tis all one, whether you do or
no: 'tis but a little more trouble to bring ye
about again; and no question, but a man may
do't, I am he. 'Tis true, as your father said, the
black ox hath not trod upon that foot of yours.
Reb. No, but the white calf hath; and so I leave
your lordship.
[Exit Rebecca.

Y. Lord W. Well, go thy ways, th' art as witty a


marmalade-eater as ever I conversed with.
Now, as I am a lord, I love her better and
better; I'll home and poetise upon her good
parts presently. Peter, here's a preparative to
my farther applications; and, Peter, be
circumspect in giving me diligent notice what
suitors seem to be peeping.
P. Ser. I'll warrant you, my lord, she's your own;
for I'll give out to all that come near her that
she is betrothed to you; and if the worst come
to the worst, I'll swear it.

Y. Lord W. Why, godamercy;


And if ever I do gain my request,
Thou shalt in braver clothes be shortly
dress'd.
[Exeunt.

Enter Old Lord Wealthy, solus.

Have the fates then conspir'd, and quite


bereft
My drooping years of all the bless'd content
That age partakes of, by the sweet aspèct
Of their well-nurtur'd issue; whose
obedience,
Discreet and duteous 'haviour, only lengthens
The thread of age; when on the contrary,
By rude demeanour and their headstrong
wills,
That thread's soon ravell'd out. O, why,
Maria,
Couldst thou abandon me now at this time,
When my grey head's declining to the grave?
Could any masculine flatterer on earth
So far bewitch thee to forget thyself,
As now to leave me? did nature solely give
thee me,
As my chief, inestimable treasure,
Whereby my age might pass in quiet to rest;
And art thou prov'd to be the only curse,
Which heav'n could throw upon mortality?
Yet I'll not curse thee, though I fear the fates
Will on thy head inflict some punishment,
Which I will daily pray they may withhold.
Although thy disobediency deserves
Extremest rigour, yet I wish to thee
Content in love, full of tranquillity.
Enter Young Lord Wealthy.

But see where stands my shame, whose


indiscretion
Doth seem to bury all the living honours
Of all our ancestors; but 'tis the fates' decree,
That men might know their weak mortality.

Y. Lord W. Sir, I cannot find my sister.

O. Lord W. I know thou canst not: 'twere too


rare to see
Wisdom found out by ignorance.

Y. Lord W. How, father! is it not possible that


wisdom should be found out by ignorance? I
pray, then, how do many magnificoes come by
it?
O. Lord W. They buy it, son, as you had need
to do.
Yet wealth without that may live more
content
Than wit's enjoyers can, debarr'd of wealth.
All pray for wealth, but I never heard yet
Of any but one that e'er pray'd for wit.
He's counted wise enough in these vain
times,
That hath but means enough to wear gay
clothes,
And be an outside of humanity. What matters
it a pin,
How indiscreet soe'er a natural be,
So that his wealth be great? that's it doth
cause
Wisdom in these days to give fools applause.
And when gay folly speaks, how vain soe'er,
Wisdom must silent sit, and speech forbear.

Y. Lord W. Then wisdom must sit as mute as


learning among many courtiers. But, father, I
partly suspect that Carracus hath got my sister.
O. Lord W. With child, I fear, ere this.
Y. Lord W. By'r Lady, and that may be true. But,
whether he has or no, it's all one: if you please,
I'll take her from under his nose, in spite on's
teeth, and ask him no leave.

O. Lord W. That were too headstrong, son;


We'll rather leave them to the will of heaven,
To fall or prosper; and though young
Carracus
Be but a gentleman of small revenues,
Yet he deserves my daughter for his virtues:
And, had I thought she could not be
withdrawn
From th' affecting of him, I had, ere this,
Made them both happy by my free consent;
Which now I wish I had granted, and still
pray,
If any have her, it may be Carracus.
Y. Lord W. Troth, and I wish so too; for, in my
mind, he's a gentleman of a good house, and
speaks true Latin.

O. Lord W. To-morrow, son, you shall ride to


his house,
And there inquire of your sister's being.
But, as you tender me and your own good,
Use no rough language savouring of distaste,
Or any uncivil terms.

Y. Lord W. Why, do you take me for a


midwife?

O. Lord W. But tell young Carracus these


words from me,
That if he hath, with safeguard of her honour,
Espons'd my daughter, that I then forgive
His rash offence, and will accept of him
In all the fatherly love I owe a child.

Y. Lord W. I am sure my sister will be glad to


hear it, and I cannot blame her; for she'll then
enjoy that with quietness which many a wench
in these days does scratch for.

O. Lord W. Come, son, I'll write


To Carracus, that my own hand may witness,
How much I stand affected to his worth.
[Exeunt.

Enter Haddit, in his gay apparel, making him


ready, and with him Lightfoot.
Had. By this light, coz, this suit does rarely! The
tailor that made it may hap to be saved, an't be
but for his good works: I think I shall be proud
of 'em, and so I was never yet of any clothes.
Light. How! not of your clothes? why then you
were never proud of anything, for therein
chiefly consisteth pride; for you never saw pride
pictured but in gay attire.
Had. True; but, in my opinion, pride might as
well be portrayed in any other shape, as to
seem to be an affecter of gallantry, being the
causes thereof are so several and divers. As,
some are proud of their strength, although that
pride cost them the loss of a limb or two by
over-daring; likewise, some are proud of their
humour, although in that humour they be often
knocked for being so; some are proud of their
drink, although that liquid operation cause them
to wear a nightcap three weeks after; some are
proud of their good parts, although they never
put them to better uses than the enjoying of a
common strumpet's company, and are only
made proud by the favour of a waiting-woman;
others are proud——
Light. Nay, I prythee, coz, enough of pride; but
when do you intend to go yonder to
Covetousness the usurer, that we may see how
near your plot will take for the releasing of your
mortgaged lands?
Had. Why, now presently; and, if I do not
accomplish my projects to a wished end, I wish
my fortunes may be like some scraping
tradesman, that never embraceth true pleasure
till he be threescore and ten.
Light. But say Hog's daughter, on whom all your
hopes depend, by this be betrothed to some
other.
Had. Why, say she were; nay more, married to
another, I would be ne'er the farther from
effecting my intents. No, coz, I partly know her
inward disposition; and, did I but only know her
to be womankind, I think it were sufficient.
Light. Sufficient for what?
Had. Why, to obtain a grant of the best thing
she had, chastity. Man, 'tis not here as 'tis with
you in the country, not to be had without
father's and mother's goodwill; no, the city is a
place of more traffic, where each one learns by
example of their elders to make the most of
their own, either for profit or pleasure.
Light. 'Tis but your misbelieving thoughts make
you surmise so: if women were so kind, how
haps you had not by their favours kept yourself
out of the claws of poverty?
Had. O, but, coz, can a ship sail without water?
had I had but such a suit as this to set myself
afloat, I would not have feared sinking. But
come, no more of need; now to the usurer: and
though

All hopes do fail, a man can want no living,


So long as sweet desire reigns in women.
Light. But then yourself must able be in giving.
[Exeunt.

Enter Albert, solus.

Conscience, thou horror unto wicked men,


When wilt thou cease thy all-afflicting wrath,
[381]
And set my soul free from the labyrinth
Of thy tormenting terror? O, but it fits not!
Should I desire redress, or wish for comfort,
That have committed an act so inhumane,
Able to fill shame's spacious chronicle?
Who but a damn'd one could have done like
me?
Robb'd my dear friend, in a short moment's
time,
Of his love's high-priz'd gem of chastity:
That which so many years himself hath stay'd
for?
How often hath he, as he lay in bed,
Sweetly discours'd to me of his Maria?
And with what pleasing passions did he suffer
Love's gentle war-siege? Then he would
relate,
How he first came unto her fair eyes' view;
How long it was ere she could brook
affection;
And then how constant she did still abide.
I then, at this, would joy, as if my breast
Had sympathis'd in equal happiness
With my true friend: but now, when joy
should be,
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like