Mastering XPages a step by step guide to XPages application development and the XSP language 1st

0 1.3K 0
Mastering XPages a step by step guide to XPages application development and the XSP language 1st

Đang tải... (xem toàn văn)

Thông tin tài liệu

Related Books of Interest IBM Lotus Connections 2.5 Planning and Implementing Social Software for Your Enterprise By Stephen Hardison, David Byrd, Gary Wood, Tim Speed, Michael Martin, Suzanne Livingston, Jason Moore, and Morten Kristiansen ISBN: 0-13-700053-7 In IBM Lotus Connections 2.5, a team of IBM Lotus Connections 2.5 experts thoroughly introduces the newest product and covers every facet of planning, deploying, and using it successfully The authors cover business and technical issues and present IBM’s proven, best-practices methodology for successful implementation The authors begin by helping managers and technical professionals identify opportunities to use social networking for competitive advantage–and by explaining how Lotus Connections 2.5 places fullfledged social networking tools at their fingertips IBM Lotus Connections 2.5 carefully describes each component of the product–including profiles, activities, blogs, communities, easy social bookmarking, personal home pages, and more Survival Guide for Lotus Notes and Domino Administrators By Mark Elliott ISBN: 0-13-715331-7 Mark Elliott has created a true encyclopedia of proven resolutions to common problems and has streamlined processes for infrastructure support Elliott systematically addresses support solutions for all recent Lotus Notes and Domino environments Survival Guide for Lotus Notes and Domino Administrators is organized for rapid access to specific solutions in three key areas: client setup, technical support, and client software management It brings together best practices for planning deployments, managing upgrades, addressing issues with mail and calendars, configuring settings based on corporate policies, and optimizing the entire support delivery process Listen to the author’s podcast at: ibmpressbooks.com/podcasts Sign up for the monthly IBM Press newsletter at ibmpressbooks/newsletters Related Books of Interest Lotus Notes Developer’s Toolbox Tips for Rapid and Successful Deployment By Mark Elliott ISBN-10: 0-13-221448-2 Lotus Notes Developer’s Toolbox will help you streamline and improve every phase of Notes development Leading IBM Lotus Notes developer Mark Elliott systematically identifies solutions for the key challenges Notes developers face, offering powerful advice drawn from his extensive enterprise experience This book presents best practices and step-by-step case studies for building the five most common types of Notes applications: collaboration, calendar, workflow, reference library, and website Web 2.0 and Social Networking for the Enterprise Guidelines and Examples for Implementation and Management Within Your Organization By Joey Bernal ISBN: 0-13-700489-3 This book provides hands-on, start-to-finish guidance for business and IT decision-makers who want to drive value from Web 2.0 and social networking technologies IBM expert Joey Bernal systematically identifies business functions and innovations these technologies can enhance and presents best-practice patterns for using them in both internal- and external-facing applications Drawing on the immense experience of IBM and its customers, Bernal addresses both the business and technical issues enterprises must manage to succeed Listen to the author’s podcast at: ibmpressbooks.com/podcasts Visit ibmpressbooks.com for all product information Related Books of Interest Understanding DB2 Security Bond, See, Wong, Chan ISBN: 0-13-134590-7 DB2 for Linux, UNIX, and Windows The Social Factor Innovate, Ignite, and Win through Mass Collaboration and Social Networking By Maria Azua ISBN: 0-13-701890-8 Business leaders and strategists can drive immense value from social networking “inside the firewall.” Drawing on her unsurpassed experience deploying innovative social networking systems within IBM and for customers, Maria Azua demonstrates how to establish social networking communities, and then leverage those communities to drive extraordinary levels of innovation The Social Factor offers specific techniques for promoting mass collaboration in the enterprise and strategies to monetize social networking to generate new business opportunities Whatever your industry, The Social Factor will help you learn how to choose and implement the right social networking solutions for your unique challenges how to avoid false starts and wasted time and how to evaluate and make the most of today’s most promising social technologies— from wikis and blogs to knowledge clouds DBA Guide, Reference, and Exam Prep, 6th Edition Baklarz, Zikopoulos ISBN: 0-13-185514-X The Art of Enterprise Information Architecture A Systems-Based Approach for Unlocking Business Insight Godinez, Hechler, Koening, Lockwood, Oberhofer, Schroeck ISBN: 0-13-703571-3 Enterprise Master Data Management An SOA Approach to Managing Core Information Dreibelbis, Hechler, Milman, Oberhofer, van Run, Wolfson ISBN: 0-13-236625-8 Mainframe Basics for Security Professionals Getting Started with RACF Pomerantz, Vander Weele, Nelson, Hahn ISBN: 0-13-173856-9 Sign up for the monthly IBM Press newsletter at ibmpressbooks/newsletters This page intentionally left blank Mastering XPages This page intentionally left blank Mastering XPages: A Step-by-Step Guide to XPages Application Development and the XSP Language Martin Donnelly, Mark Wallace, and Tony McGuckin IBM Press Pearson plc Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Cape Town • Sydney • Tokyo • Singapore • Mexico City ibmpressbooks.com The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein © Copyright 2011 by International Business Machines Corporation All rights reserved Note to U.S Government Users: Documentation related to restricted right Use, duplication, or disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corporation IBM Press Program Managers: Steven M Stansel, Ellice Uffer Cover design: IBM Corporation Associate Publisher: Dave Dusthimer Marketing Manager: Stephane Nakib Executive Editor: Mary Beth Ray Publicist: Heather Fox Senior Development Editor: Christopher Cleveland Managing Editor: Kristy Hart Designer: Alan Clements Senior Project Editor: Lori Lyons Technical Reviewers: Maureen Leland, John Mackey Copy Editor: Sheri Cain Indexer: Erika Millen Senior Compositor: Gloria Schurick Proofreader: Kathy Ruiz Manufacturing Buyer: Dan Uhrig Published by Pearson plc Publishing as IBM Press IBM Press offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests For more information, please contact U S Corporate and Government Sales 1-800-382-3419 corpsales@pearsontechgroup.com For sales outside the U S., please contact International Sales international@pearson.com The following terms are trademarks of International Business Machines Corporation in many jurisdictions worldwide: IBM, Notes, Lotus, Domino, Symphony, Quickr, Sametime, Lotusphere, Rational, WebSphere, LotusScript, and developerWorks Other product and service names might be trademarks of IBM or other companies A current list of IBM trademarks is available on the Web at “Copyright and trademark information” at www.ibm.com/legal/copytrade.shtml Oracle, Java and all Java-based trademarks and logos are trademarks or registered trademarks of Oracle and/or its affiliates Microsoft, Windows, ActiveX, and Internet Explorer are trademarks of Microsoft Corporation in the United States, other countries, or both Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both Other company, product, or service names may be trademarks or service marks of others Library of Congress Cataloging-in-Publication Data Donnelly, Martin, 1963Mastering XPages : a step-by-step guide to XPages : application development and the XSP language / Martin Donnelly, Mark Wallace, Tony McGuckin p cm Includes bibliographical references and index ISBN 978-0-13-248631-6 (pbk : alk paper) Internet programming XPages Application software—Development Web site development I Wallace, Mark, 1967- II McGuckin, Tony, 1974- III Title QA76.625.D66 2011 006.7’6—dc22 2010048618 All rights reserved This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise For information regarding permissions, write to: Pearson Education, Inc Rights and Contracts Department 501 Boylston Street, Suite 900 Boston, MA 02116 Fax (617) 671 3447 ISBN-13: 978-0-13-248631-6 ISBN-10: 0-13-248631-8 Text printed in the United States on recycled paper at R.R Donnelley in Crawfordsville, Indiana First printing January 2011 I dedicate this book to the memory of my dear sister Anne, the brightest and the best —Martin For Dee, Sam, and Becky: I couldn’t have contributed to this book without the support, encouragement, and unending patience of my wonderful wife Thank you, Dee —Mark I want to thank some great people for my involvement in this book First, it would not have happened without the encouragement and direction of my lead architect (and co-author) Martin; thank you for the great opportunity Second, I want to thank my development manager, Eamon, and senior technical architect, Phil, who had to keep things going without a full-time engineer, and yet both remained upbeat throughout the process Finally, I dedicate my contribution to this book to my parents, family, and especially my wife, Paula, and daughter, Anna-Rose, for putting up with a part-time husband and dad—I love you both! —Tony Contents Foreword by Philippe Riand Preface xx xxiv Part I: Getting Started with XPages Chapter An Introduction to XPages XPages Fundamentals Brand New Technology? A Different Development Paradigm The More Things Change, the More Things Stay the Same New Horizons Conclusion Chapter Getting Everything You Need Downloads, Versions, and Locations Installing Domino Designer Installing Client Fix Packs Client Configuration Quick Tour of Domino Designer Domino Designer Welcome Screen Domino Designer Perspective Creating a New Application Creating an XPage Previewing in the Notes Client Previewing in a Web Browser Adding a Control to an XPage Conclusion 7 9 10 11 11 12 13 14 15 16 18 18 21 22 xii Mastering XPages Chapter Building Your First XPages Application Laying the Foundations Forms and Views Building an XPages View Completing the CRUD Conclusion 23 24 26 31 36 42 Part II: XPages Development: First Principles 43 Chapter Anatomy of an XPage 45 What Exactly Is an XPage? Understanding XSP Tag Markup Getting Started with XML XPages XML Syntax Simple Properties Complex Properties Complex Values Computed Properties Data Binding XPages Tags Data Sources Domino Document Domino View Data Context Controls Editing Controls Command Controls Selection Controls Display Controls File-Handling Controls Containers Panel Table View Data Table Repeat Include Page Tabbed Panel Section XPage Resources Script Library Style Sheet Resource Bundle 46 47 47 50 52 54 54 55 59 60 61 61 62 63 64 64 70 74 82 84 87 87 90 91 94 95 99 99 100 101 101 103 104 Contents xiii Dojo Module Generic Head Resource Metadata Resource Converters Validators Simple Actions Client-Side Scripting HTML Tags Conclusion Chapter XPages and JavaServer Faces What Is JavaServer Faces? JSF Primer How Does XPages Extend JSF? XML-Based Presentation Tier Request Processing Lifecycle User Interface Component Model Standard User-Interface Components Value Binding and Method Binding Expression Evaluation XPages Default Variables Conclusion Chapter Building XPages Business Logic Adding Business Logic Using the xp:eventHandler Tag Simple Actions Change Document Mode Confirm Action Create Response Document Delete Document Delete Selected Documents Execute Client Script Execute Script Modify Field Open Page Publish Component Property Publish View Column Save Data Sources Save Document Set Component Mode Set Value Action Group 105 106 106 107 110 118 125 127 128 129 130 131 138 141 142 143 148 152 154 156 157 157 160 167 168 169 170 171 172 173 173 174 175 176 177 179 180 182 183 184 xiv Mastering XPages Using JavaScript with XPages Server-Side JavaScript Client JavaScript Conclusion 186 186 206 211 Part III: Data Binding 213 Chapter Working with Domino Documents 215 Domino Document Data Source Creating and Editing Documents Controlling URL Parameter Usage Creating Response Documents Executing Form Logic Managing Concurrent Document Updates Multiple Document Data Sources Document Data Source Events Common Data Source Properties Miscellaneous Data Source Properties Working with Domino Documents—Programmatically! Simple Actions JavaScript Rich Documents Conclusion Chapter Working with Domino Views databaseName Property View Data Source Filters categoryFilter Property search, searchMaxDocs Properties parentId Property ignoreRequestParams Property keys, keysExactMatch Properties Other View Content Modifiers startKeys Property expandLevel Property A Page with Two Views requestParamPrefix Property When Is a View Not a View? Go Fetch! Or Maybe Not loaded, scope Properties postOpenView, queryOpenView Properties Caching View Data Sorting Columns Conclusion 216 219 220 220 224 227 228 231 233 234 235 235 236 238 242 243 245 246 246 249 251 252 253 256 256 257 259 260 261 262 263 263 265 270 271 Contents Chapter xv Beyond the View Basics Pick a View Control, Any View Control The View Control: Up Close and Personal Column Data Like You’ve Never Seen Before Simple View Panel Make Over Working with Categories View Properties and View Panel Properties Data Table Building a Mini Embedded Profile View using a Data Table Repeat Control A Repeat Control Design Pattern Nested Repeats The Rich Get Richer Some Fun with the Pager Conclusion Part IV: Programmability Chapter 10 Custom Controls Divide and Conquer Getting Started with Custom Controls Using Property Definitions Property Tab Validation Tab Visible Tab Property Definitions Summary Using the compositeData Object Send and You Shall Receive Multiple Instances and Property Groups Custom Control Design Patterns Aggregate Container Pattern Layout Container Pattern Conclusion Chapter 11 Advanced Scripting Application Frameworks AJAX and Partial Refresh Partial Refresh: Out-of-the-Box Style! Partial Refresh: Doing-It-My-Way Style! Event Parameters Dojo Integration dojoTheme and dojoParseOnLoad Properties dojoModule Resource dojoType and dojoAttributes Properties Integrating Dojo Widgets and Extending the Dojo Class Path 273 273 276 277 279 293 301 305 311 316 317 318 320 321 324 325 327 328 329 337 340 343 345 346 346 352 355 357 357 358 365 367 367 369 369 376 384 386 387 388 389 390 xvi Mastering XPages Working with Traditional Notes/Domino Building Blocks Working with @Functions, @Commands, and Formula Language Working with Agents, In-Memory Documents, and Profile Documents Managed Beans Conclusion Chapter 12 XPages Extensibility How to Create a New User Interface Control Example Component Let’s Get Started Create the Initial Application Add Package Explorer to the Domino Designer Perspective Add a Java Source Code Folder Building a Component Create a UI Component Extension Class Create Tag Specificaton (.xsp-config) for the UI Component Extension Create a Renderer and Register It in the Application Configuration (faces-config.xml) Quick Test Application to Verify Everything Is OK So Far Working with Component Properties Component Properties and Attributes Adding a Property to a Component State Holder: Saving State Between Requests Specifying Simple Properties Inheriting xsp-config Properties Create the Initial xsp-config Definitions Create base.xsp-config Create an Interface to Match the Group Property Definition in base.xsp-config Revisit the Component Properties in Domino Designer Specifying Complex Properties Complete the xsp-config for the UISpinner Component Complete the UI Component Extension, UISpinner Complete the Renderer UISpinnerRenderer Create a Sample Application Using the UISpinner Component Take Your New UI Component Extension for a Test Drive Create a Backing Bean Register the Backing Bean Create the Final Test Application Nice Look and Feel Test to Ensure That It All Works! Where to Go From Here XPages Extensibility API Developers Guide XPages Extension Library IBM developerWorks Conclusion 401 402 405 412 419 421 422 423 424 424 424 426 428 428 431 434 437 438 438 439 440 440 441 446 446 450 452 453 464 473 477 483 483 483 486 486 491 491 491 492 492 492 493 Contents xvii Chapter 13 XPages in the Notes Client Think Inside the Box Getting Started with XPages in the Notes Client 3, 2, Lift Off Bookmarks Working Offline One of These Things Is Not Like the Other Other Subtle Differences XPages: A Good Notes Citizen Introducing enableModifiedFlag and disableModifiedFlag Keeping Tabs on Your Client Apps Notes Links Versus Domino Links Some Debugging Tips XPages and Composite Applications Making a Component of an XPages Application Is Anyone Out There? Creating a Component that Listens to Your XPages Component Assembling a Composite Application: Aggregating the XPages Discussion Component and Notes Google Widget Hey, This Is a Two-Way Street! A Component May Receive and Publish Events! Further Adventures with Composite Applications Part V: Application User Experience Chapter 14 XPages Theming It Used to Be Like That But Not Anymore! Styling with Style! Setting the Style Property Manually Understanding How the Style Property Is Used Computing the Style Property Styling with Class! Getting Something for Nothing! Understanding How the styleClass Property Is Used Computing the styleClass Property Working with Extended styleClass and style Properties Theming on Steroids! What Is a Theme? What Can You Do with a Theme? Understanding Theme Architecture and Inheritance Working with a Theme Theme Resources Resource Paths Theme Properties, themeId, Control Definitions, and Control Properties Conclusion 495 496 498 499 501 503 507 508 511 513 516 520 525 528 529 531 533 536 540 541 543 543 545 550 551 552 552 553 559 561 563 567 567 568 569 576 587 597 606 620 xviii Mastering XPages Chapter 15 Internationalization Using Localization Options Localization with Resource Bundle Files Setting Localization Options Testing a Localized Application Working with Translators Merging XPage Changes Gotchas! Localizing Computed Expressions and JavaScript Adding a Resource Bundle Localizing Computed Expressions Localizing Client-Side JavaScript Localizing Script Libraries Server-Side Script Libraries Client-Side Script Libraries International Enablement Locales in XPages Deprecated Locale Codes Conclusion Part VI: Performance, Scalability, and Security Chapter 16 Application Performance and Scalability Golden Rules Understanding the Request Processing Lifecycle GET-Based Requests and the JSF Lifecycle POST-Based Requests and the JSF Lifecycle Reducing CPU Utilization GET- Versus POST-Based Requests Partial Refresh Partial Execution Mode Reducing Memory Utilization HTTPJVMMaxHeapSize and HTTPJVMMaxHeapSizeSet Parameters xsp.persistence.* Properties dataCache Property Conclusion Chapter 17 Security Notes/Domino Security and XPages Server Layer of Security Application Layer of Security Design Element Layer of Security Document Layer of Security 621 622 623 624 626 628 631 633 636 637 638 639 640 640 641 643 644 648 650 651 653 654 655 656 656 658 658 663 665 668 669 669 670 672 673 673 674 675 677 684 Contents xix Workstation ECL Layer of Security Useful Resources Let’s Get Started Creating the Initial Application Implementing ACLs Sign the XPages with Your Signature Programmability Restrictions Sign or Run Unrestricted Methods and Operations Sign Agents to Run on Behalf of Someone Else Sign Agents or XPages to Run on Behalf of the Invoker Sign Script Libraries to Run on Behalf of Someone Else Restricted Operation XPages Security Checking NSF ClassLoader Bridge XPages Security in the Notes Client Execution Control List (ECL) Active Content Filtering Public Access Setting Public Access for XPages Checking for Public Access in XPages SessionAsSigner Troubleshooting XPages Java Security Exceptions Conclusion Part VII: Appendixes Appendix A XSP Programming Reference XSP Tag Reference XSP Java Classes Notes/Domino Java API Classes XSP JavaScript Pseudo Classes Appendix B XSP Style Class Reference XSP CSS Files XSP Style Classes Appendix C Useful XPages Sites on the Net Index 686 687 687 687 689 690 691 692 692 693 693 693 695 695 696 697 699 702 703 703 704 706 707 709 711 711 712 714 715 719 719 720 727 729 Foreword: Revolution Through Evolution I never got a chance to meet the inventors of Notes®, but these guys were true visionaries Their concepts and ideas of 20 years ago still feed today’s buzz They invented a robust “NO SQL” data store, provided a social platform with collaboration features, and made the deployment and replication of applications easy it is certainly no accident that Notes became so popular! Backed by a strong community of passionate developers dedicated to the platform, it elegantly solves real problems in the collaboration space by bringing together all the necessary components As a developer, it makes you very productive Lotus Notes is also a fabulous software adventure and definitely a model for other software projects At a time when technology evolves at unprecedented speed, where new standards appear and deprecate quickly, Lotus Notes adapts by keeping up to date Over the past 20 plus years, Notes/Domino® has continually embraced diverse technologies in different domains: HTTP, XML, JavaScript™, Basic, Java™, POP/IMAP, LDAP, ODBC, just to name a few this makes it unique in the software industry Best of all, this is done while maintaining full compatibility with the previous releases This reduces the risk for IT organizations and makes their long-term investment safer Applications that were built about two decades ago on top of Windows® (remember?) can be run without modification on the latest release of Notes/Domino, using any modern 64-bit operating system, including Linux® and MAC-OS! Continuity is the master word here, paired with innovation But, the world evolves Software platforms in the old days were just proprietary, providing all the features they required by themselves The need for integration wasn’t that high However, as IT has matured over time, most organizations nowadays rely on heterogeneous sets of software that have to integrate with each other Starting with version 8, the Notes client became a revolutionary integration platform Not only does it run all of your traditional Notes/Domino applications, but it also integrates a Java web container, provides a composite application framework, embeds Symphony™, offers connectors to Quickr®, Sametime®, Lotus Connections, and so on This was a great accomplishment—kudos to the Notes team Foreword xxi At the same time, a parallel evolution saw the emergence of a more web-oriented world An increasing set of applications, which traditionally required a specific proprietary client, started to become fully available through just a regular web browser Google is certainly deeply involved in this mutation New frameworks, languages, and libraries were designed to support this new nodeployment model So, what about Notes/Domino? How can it be remain relevant in this new, ever-changing world? Of course, the Domino server includes an HTTP server that goes all the way back to R4.5 But, although it allows you to pretty much everything, the cost of developing a web application, and the amount of required experience, was prohibitive Moreover, the development model uses a proprietary page-definition language that is not intuitive for newcomers to the platform Although not insurmountable, this was certainly a significant barrier to entry It became clear that Domino web-application development (including Domino Designer) needed the same kind of revolution that the Notes client had undergone True to our core values, however, this had to really be an evolution, where existing investment could be preserved, while throwing open the door to the new world In essence, a revolution through an evolution During this time, I was leading a team at IBM® working on a development product called Lotus Component Designer (LCD) Its goal was to provide a Notes/Domino-like programming model on top of the Java platform, targeting the Lotus Workplace platform It included most of the ingredients that made Notes/Domino a successful application development platform, while at the same time being based upon standard technologies: Java, JavaServer Faces (JSF), and Eclipse Designed from the ground-up to generate top-notch web applications, it included a lot of new innovations, like the AJAX support, way before JSF 2.0 was even spec’d out What then could have been a better fit for Notes/Domino app dev modernization? The asset was solid, the team existed, and the need was great, so it became the natural candidate for integration into Domino An initial integration was achieved in a matter of a few weeks, and this is how the XPages story started! When I joined the Notes Domino team four years ago (yes, time is running fast!), my mission was to make that revolution happen, starting with web applications Taking over such a mission was intimidating because Domino has such a fabulous community of developers with unrivaled experience who obviously know much more about the product than I ever could In fact, one of our business partners recently showed me a picture of five key employees and pointed out that they collectively represent more than 80 years of Notes/Domino development experience! In addition to this, the Lotus Notes/Domino development team is a well-established one, with mature processes and its own unique culture and habits The XPages team was not only new to this world, but located geographically on the other side of it—in Ireland! The challenge thus became one of gaining acceptance, both internally and externally This was a risky bet, because people might have easily just rejected the XPages initiative and pushed for another solution But, we were pleasantly and encouragingly surprised The first reactions were very positive There was definitely room to deliver the innovation that the community so badly needed Notes/Domino 8.5 was the first release developed using an agile methodology As it happened, that perfectly suited a new technology like XPages It allowed us to communicate a lot xxii Mastering XPages with the community, share design decisions, get advice, and modify our development plan dynamically We had been, and still are, listening closely to the community through many and varied sources like blogs, wikis, forums, and of course, direct communication We are most definitely dedicated to putting our customers in a winning situation Everything we is toward this goal: We truly understand that our success is our customers’ success In this area, the XPages development team showed an impressive commitment For example, we organized not one, but two workshops in our development lab months before releasing the product! And it paid off: We introduced happy customers on stage at Lotusphere® 2009, a mere 15 days after the official release of the Domino 8.5 Their testimonials were encouraging and have not been proved wrong since, as the XPages adoption curve moves ever onward and upward Many XPages-based solutions were shown at Lotusphere 2010, and Lotusphere 2011 promises to be another great stage with a lot of already mature solutions waiting to be announced The team also wrote numerous articles in the Domino Application Development wiki, recorded many videos, and has been responsive on the different forums This is also a major change where the development team is not isolated in its sterilized lab, but interacting positively with the broader community The revitalization of openNTF.org is another example The number of its monthly hits shows just how successful it is Many partners have told me that they always look for already available reusable components before deciding to develop their own, and openNTF is just a fantastic resource in this regard So, what’s next? Are we done? Certainly not! We have new challenges coming in, particularly with the next generation of browsers and platforms We need to evolve XPages to generate applications that can take advantage of the new client capability We need XPages to be tightly integrated with the rest of IBM Collaboration Services portfolio (a.k.a Lotus portfolio) We need to support the new devices, such as smartphones and tablet PCs We want to make sure that XPages plays a leading role with the next generation of Lotus Software (code name Vulcan) But, beyond the technology, we also have the challenge of transforming the way we create and deliver software We want to make the Notes/Domino technology more open We want to make the development process more transparent We want to get feedback earlier, and we even want the community to contribute to that effort We’re all here to make it better, aren’t we? The answer, in my opinion, is to open source some parts of the platform OpenNTF is becoming our innovation lab, delivering technology early, breaking the regular release cycles It allows us to be responsive to the community needs and then integrate the components later in the core product Recently, we successfully experienced this with the new XPages Extension Library The feedback we received was very positive, so we want to continue in this direction Stay tuned Notes/Domino is the platform of the future! Finally, this story wouldn’t have happened without a great XPages and Domino Designer team For the quality of the work, the innovation path, the willingness to take on new challenges, the customer focus well, for many aspects, this team is seen as exemplary in the broader Lotus organization I really feel lucky and proud to be part of it This book’s three authors are also key members Each one of them has worked on different areas of XPages; the gang of writers cannot Foreword xxiii be better staffed Martin is the team lead in Ireland, and he designed the Notes client integration and the data access part Mark is a core runtime expert, and he has been involved since the early prototypes Tony is our applications guy, in charge of the new generation of template applications He has also been successful on many customer projects Finally, helping them is Jim Quill, our security expert and general XPages evangelist With this book, you definitely get the best of the best! I have no doubt that you’ll learn a lot by reading it, whether you’re a beginner or an XPages hacker Enjoy, the story has just begun! Philippe Riand XPages Chief Architect Preface XPages made its official public debut in Notes/Domino version 8.5, which went on general release in January 2009 At the annual Lotusphere conference that same month in Orlando, Florida, XPages was featured directly or indirectly in a raft of presentations and workshops, including the keynote session itself, as the technology was introduced to the broad applicationdevelopment community Throughout the conference, it was variously described as a new framework for Web 2.0 development, a strategic move to reinvigorate the application-development experience, a standards-based runtime that would greatly boost productivity for the Domino web developer to quote but a few! Fancy claims indeed, but then again, Lotusphere has always been the stage that heralded the arrival of the “next big things” in the Notes/Domino community Fast forward to the present time: It’s fair to say that all these claims (excluding maybe one or two made much, much later into those Floridian evenings) were prophetic and XPages, as a technology, is indeed living up to its promise in the real world Evidence of this is all around us A vibrant XPages development community has evolved and thrives Respected bloggers wax enthusiastic about the latest XPages tips and tricks XPages contributions abound in OpenNTF.org, while the Notes/Domino Design Partner forum sees a steady flow of questions, comments, and, of course, requests for new cool features A recurring pattern evident in the flow of requests is the call for better documentation XPages is a powerful Java runtime with a host of rich and sophisticated features that runs the entire app dev gamut In the Notes/Domino 8.5 release, would-be XPages developers were left to their own devices to get up to speed with the technology Typical approaches for the resourceful newbie developer included foraging for XPages programming patterns in the standard Notes Discussion template (which shipped with an out-of-the-box XPages web interface), scouring the limited Help documentation, and sharing random enablement materials that had started to appear on the web Although all these, along with a sizable dollop of developer ingenuity, often worked remarkably well for those with large reserves of determination, the value of a single source of XPages information cannot be understated This book’s goal is to fill that gap and provide a single comprehensive guide that enables readers to confidently take on, or actively participate in, a realworld XPages application-development project Preface xxv Approach This book’s objective is to impart as much practical XPages knowledge as possible in a way that is easy for the reader to digest The authors seek to cover all aspects of the XPages development spectrum and to engage the reader with hands-on problems wherever possible Most chapters come with a sample application that provides plentiful exercises and examples aimed at enabling you to quickly and efficiently solve everyday real-world use cases These resources are located on the web at www.ibmpressbooks.com/title/9780132486316, so waste no time in downloading before getting started! Tinker, Tailor, Soldier, Sailor? Our Diverse Reading Audience Although XPages is a new technology that offers a development model familiar to the average web developer (and the above-average ones, too!), many traditional Notes/Domino development skills can also be harnessed to good effect One challenge in writing this book is that no single developer profile really defines the reader audience For example, is the typical reader a webapplication developer coming to the Notes/Domino platform or a Notes/Domino web developer wanting to learn XPages? In fact, since the release of Notes version 8.5.1, the reader may well be a Notes client application developer seeking to write new XPages applications for the Notes client or customize web applications that can now be run offline in that environment Finally, a fourth category of reader may be the novice developer, for whom all this stuff is pretty much new! Which one are you? Or you may indeed be graced with the fine talents of bilocation and can appear in two of these camps at once! Anyway, suffice to say that there inevitably will be aspects to several topics that are peculiar to a particular category of audience Such content will typically be represented in this book as sidebars or tips in the context of the larger topic Other cases might merit a dedicated section or chapter, such as Part IV, “Programmability,” which contains a chapter that deals with all the details of XPages in the Notes client, while Part VI, “Performance, Scalability, and Security,” has an entire chapter dedicated to the topic of application security Other Conventions Any programming code, markup, or XSP keywords are illustrated in numbered listings using a fixed width font User-interface elements (menus, links, buttons, and so on) of the Notes client, Domino Designer, or any sample applications are referenced using a bold font Visual representations of the design-time experience or runtime features are typically captured as screen shots and written as numbered figures, using superimposed callouts where appropriate xxvi Mastering XPages How This Book Is Organized This book is divided into seven parts to separately address the many different aspects of XPages software development in as logical a manner as possible: Part I, “Getting Started with XPages”: This part gets you familiar with XPages at a conceptual level to get you up and running quickly with the technology and get you comfortable with the overall application development paradigm • Chapter 1, “An Introduction to XPages”: Here, you are introduced to the history of XPages and given some high-level insights into its design principles in order for you to understand exactly what it is and what it is not This is all about giving you the right context for XPages by defining the problems it solves, the technologies on which it is based, and where it might go in the future • Chapter 2, “Getting Everything You Need”: This chapter concerns itself with the practical business of obtaining, installing, and configuring your XPages development environment and successfully walking you through your first “Hello World” XPage! • Chapter 3, “Building Your First XPages Application”: This chapter aims to provide a breadth-first hands-on experience of building a simple web application using the XPages integrated development environment (a.k.a Domino Designer) This is really just an introductory practical to get your feet wet and ensure you are comfortable with the basics of the application development model before diving any deeper Part II, “XPages Development: First Principles”: This part is mostly architectural in nature and aims to give you an appreciation of what’s happening under the XPages hood This is an essential prerequisite to some of the more advanced topics, like XPages performance and scalability • Chapter 4, “Anatomy of an XPage”: This chapter examines the XSP markup language and gives a simple example of all the standard elements (controls and such) that can be used in an XPage It provides a great broad-based view of XPages basics • Chapter 5, “XPages and JavaServer Faces”: This chapter looks at JavaServer Faces (JSF), which is the web-application development framework on which XPages is based It looks at some core JSF design points and how XPages leverages and extends the framework • Chapter 6, “Building XPages Business Logic”: This chapter is a primer for XPages programmability It introduces the various tools that can be used to implement XPages business logic so that you will be ready to work with the practical examples that are coming down the pike Part III, “Data Binding”: This part is really about how XPages reads and writes Notes data XPages comes with a library of visual controls that are populated at runtime using a process known as data binding The mechanics of the data binding process is explored in depth for Notes views and documents Preface xxvii • Chapter 7, “Working with Domino Documents”: This chapter focuses on reading and writing Notes documents via XPages Advanced use cases are explored and every design property on the Domino document data source is explained and put through its paces using practical examples • Chapter 8, “Working with Domino Views”: In this chapter, the Domino view data source is dissected and examined, property by property Again, practical exercises are used to drive home the material under discussion • Chapter 9, “Beyond the View Basics”: Working with Notes/Domino views is a large subject area, so much so that it demands a second chapter to cover all the details This chapter looks at the various container controls that are available in the standard XPages control library, whose job it is to display view data in different formats and layouts in order to support a myriad of customer use cases Part IV, “Programmability”: This part covers the black art of programming—essentially how to code your applications to everything from the most basic user operation to writing your own controls that implement completely customized behaviors This part concludes with a look at XPages in the Notes client and considers cross-platform application development issues • Chapter 10, “Custom Controls”: This chapter explains the “mini-XPage” design element that is the custom control It explains how to leverage the custom control in order to “componentize” your application and then maximize the reuse of your XPages development artifacts • Chapter 11, “Advanced Scripting”: Advanced scripting is an umbrella for many cool topics, like AJAX, Dojo, @Functions, agent integration, managed beans, and so forth This is a must for anyone looking to add pizzazz to their XPages applications • Chapter 12, “XPages Extensibility”: This chapter explains how to use the XPages extensibility APIs to build and/or consume new controls This is an amazingly powerful feature that has only recently become available and is well worth exploring once you have mastered XPages fundamentals • Chapter 13, “XPages in the Notes Client”: XPages in the Notes client initially explains how you can take your XPages web applications offline and then goes on to highlight how you can take advantage of powerful features of the client platform itself, and how to manage applications that run in both environments Part V, “Application User Experience”: This part is all about application look and feel You learn not just how to make your apps look good and behave well, but how to so for an international audience! • Chapter 14, “XPages Theming”: This chapter teaches you how to manage the appearance and behavior of your application’s user interface It provides an in-depth look at ad-hoc XPages application styling using cascading style sheets, as well as the main features of the standard XPages UI themes, and explains how to create your own customized themes xxviii Mastering XPages • Chapter 15, “Internationalization”: Read this chapter to learn how your XPages applications can be translated so that they look, feel, and behave as native applications in any geographical locale Part VI, “Performance, Scalability, and Security”: Up to this point this book has concentrated on the skills and tools you need to know to develop state-of-the-art collaborative applications Part VI shifts to deployment and what you need to to make sure your applications meet customer expectations in terms of performance, scalability, and security • Chapter 16, “Application Performance and Scalability”: This chapter highlights various tips and tricks that will enable you to tune your XPages application for optimal performance and scalability in various deployment scenarios • Chapter 17, “Security”: Learn about application security issues and considerations and see how XPages integrates with the Domino server and Notes client security models Part VII, “Appendixes” • Appendix A, “XSP Programming Reference”: This appendix points to a collection of definitive reference sources that describe all the details of the XSP tags, Java and JavaScript classes It provides examples of how to use these resources to find the information you need • Appendix B, “XSP Style Class Reference”: This appendix identifies all the standard XPages CSS files and style classes used to build XPages application user interfaces It’s an essential quick reference for Chapter 14 • Appendix C, “Useful XPages Sites on the Net”: A snapshot of the authors’ favorite XPages websites at the time of writing This list of sites should help you find whatever it is you need to know about XPages that isn’t found in this book Acknowledgments This book was a new and eventful journey for all three authors as none of us had been down the book-writing road before At times, the trip became a little more arduous than we had anticipated, but we received a lot of help from some great people along the way We first want to thank our contributing author and colleague in IBM Ireland, Jim Quill, who we press-ganged at the eleventh hour and cajoled into writing a couple of chapters on the specialized topics of extensibility and security, respectively Jim duly delivered, and we could not have met our project deadlines without him—just goes to show, a friend in need is a friend indeed! We are happy to say that we are still on speaking terms with our two excellent and dedicated technical reviewers, Maureen Leland and John Mackey Thanks to you both for keeping us honest and being positive and insightful at all times A sincere thank you to those who helped get this book proposal off the ground—especially Eamon Muldoon, Pete Janzen, and Philippe Riand, for their encouragement and advice along the way We are indebted to Maire Kehoe who always parachutes in for us to solve thorny problems at the drop of a hat—where would we be without you! Padraic Edwards and Teresa Monahan deserve our kudos for helping out on composite application use cases, and to Teresa again for her CK Editor brain dump And because all the authors are based in Ireland, you can well imagine that we took every opportunity to lean on the other members of the XPages runtime team at the IBM Ireland lab For that help, we want to collectively thank Brian Gleeson, Brian Bermingham, Darin Egan, Dave Connolly, Edel Gleeson, Gearóid O’Treasaigh, Lisa Henry, Lorcan McDonald, Paul Hannan, and Willie Doran We want to express our thanks to Robert Perron for some articles and documentation utilities that we are glad to leverage in a couple of places in this book Thanks also to Thomas Gumz for some collaborative demo work we did at a dim and distant Lotusphere that is still worthy of print today! We are privileged to say there is a long list of folks at IBM past and present who have helped push the XPages cause forward over its eventful course thus far Thanks to Azadeh Salehi, Bill Hume, Brian Leonard, Dan O’Connor, Dave Kern, David Taieb, Girish P Baxi, Graham O’Keeffe, Ishfak Bhagat, Jaitirth Shirole, Jeff deRienzo, Jeff Eisen, Jim Cooper, John Grosjean, xxx Mastering XPages John Woods, Kathy Howard, Margaret Rora, Matthew Flaherty, Mike Kerrigan, Na Pei, Peter Rubinstein, Russ Holden, Santosh Kumar, Scott Morris, Simon Butcher, Simon Hewett, Srinivas Rao, Steve Castledine, Steve Leland, Tom Carriker, Xi Pan Xiao, and Yao Zhang Apologies to any IBMers accidentally omitted; let us know and we’ll be sure to include you in the reprints! To our friends at IBM Press—in particular Mary Beth Ray, Chris Cleveland, Lori Lyon, and Gloria Schurick—it may be a well-worn cliché, but it truly was a pleasure working with you guys! And on the IBM side of that relationship, we echo those sentiments to Steven Stansel and Ellice Uffer Finally, a great big THANK YOU, as always, to our customers and business partners, particularly the early adopters who got behind XPages at the get-go and made it the success that it is today! About the Authors The authors of this book have a number of things in common All three hail from Ireland, work for the IBM Ireland software lab, and have made significant contributions to the development of XPages over the past number of years Martin Donnelly is a software architect and tech lead for the XPages runtime team in IBM Ireland and has worked on all three XPages releases from Notes/Domino 8.5 through 8.5.2 Prior to this, Martin also worked on XFaces for Lotus Component Designer and on JSF tooling for Rational® Application Developer In the 1990s while living and working in Massachusetts, he was a lead developer on Domino Designer Now once again based in Ireland, Martin lives in Cork with his wife Aileen, daughters Alison, Aisling, and Maeve, and retired greyhounds Evie and Chelsea Outside of work, he confesses to playing soccer on a weekly basis, and salmon angling during the summer when the opportunity presents itself Mark Wallace is a software architect working in the IBM Ireland software lab In the past, he worked on the XSP runtime, which was developed for Lotus Component Designer and subsequently evolved into the XPages runtime He has a keen interest in programming models and improving developer productivity Mark has worked in Lotus and IBM for more than 15 years on various products and is currently working on Sametime Unified Telephony Mark lives in Dublin with his wife and two children and spends as much time as possible in the Ireland’s sunny south east enjoying fishing and kayaking with his family Tony McGuckin is a senior software engineer in the IBM Ireland software lab Having studied software engineering at the University of Ulster, he began his career with IBM in 2006 working in software product development on the component designer runtime before moving into the XPages core runtime team When not directly contributing to the core runtime, Tony is busy with software research and development for the next generation of application development tooling, and also engaging directly with IBM customers as an XPages consultant Tony enjoys spending time with his wife and daughter, and getting out into the great outdoors for hill walking and the occasional chance to some hunting in the surrounding hillsides of his native County Derry xxxii Mastering XPages Contributing Author Jim Quill is a senior software engineer for the XPages team in IBM Ireland He is relatively new to the Notes/Domino world, joining IBM just over two years ago at the tail end of the first XPages release in Domino 8.5 Previous to IBM, Jim enjoyed more than 13 years at Oracle Ireland There, he worked in areas such as product development and database migration technology, and he was both principal software engineer and technical architect for a number of internal Oracle® support systems Jim lives in the coastal village of Malahide, north County Dublin, with his wife and four children When not acting as the kids’ taxi, he continues to play competitive basketball way past his retirement date PART I Getting Started with XPages An Introduction to XPages Getting Everything You Need Building Your First XPages Application 23 This page intentionally left blank C H A P T E R An Introduction to XPages For readers new to XPages, the first step on this journey is to examine the original objectives of XPages, to understand what it is from a technical standpoint, and to recognize the strategic value it offers as an application development technology Even for those with some real XPages experience under their belt, a reminder of these XPages fundamentals does no harm XPages Fundamentals In a nutshell, XPages is the new web-application development framework for Notes/Domino That is, from version 8.5 forward, XPages is the recommended approach for anyone writing a new web application or embarking on upgrading such an existing application to a Web 2.0 level XPages is a Java runtime environment that supports all the defining features of Web 2.0, and it extends a standards-based framework known as JavaServer Faces (JSF) This JSF standard is commonly used as a base technology across many other commercial web-application development offerings, such as IBM Rational Application Developer, Oracle JDeveloper, JBoss, and so on The implications of that last statement could be a cause for concern among a sizeable section of the Notes/Domino application development community, so it’s best to qualify it immediately in a number of important ways Yes, JSF is an industry standard for Java developers engaged in J2EE™ application development, but no, it is not necessary to be a Java/Java Platform, Enterprise Edition (J2EE) developer to use XPages, and there is no requirement to write any Java code to build a “typical” XPages application In fact, the existence of JSF as the foundation layer of XPages is completely transparent to the mainstream Domino application development experience, and any direct usage should be completely unnecessary for the vast majority of applications Chapter An Introduction to XPages XPages is based on JSF version 1.1, although note that some important fixes from JSF version 1.2 and 2.0 have been applied to the XPages foundation layer; therefore, in reality, the XPages base version is more like 1.1++ This was done on a case-by-case basis to either solve a specific problem or take advantage of particular performance optimization that was introduced to JSF after the 1.1 release To date, there has not been an opportune time in the XPages release cycles to rebase it completely on a more recent JSF version, although this will no doubt happen in the future Also note that JSF version 1.1 was developed through the Java Community Process (JCP) under Java Specifications Request (JSR) 127 So, what’s all this JCP and JSR mumbo jumbo and why should you care? Well, according to Wikipedia, the JCP “is a formalized process that allows interested parties to get involved in the definition of future versions and features of the Java platform.” The JSR, on the other hand, is the instrument used to describe the nitty-gritty details of an actual feature specification Thus JSF is not an IBM creation, but the collective result of collaborations between many technical leaders in the industry to come up with an agreed-upon framework that enables all players to build better Java tools and applications In that light, it’s easy to argue that building XPages on top of a JSF platform can only be a good thing! Among the many benefits XPages derives from JSF is the capability to target multiple platforms (for example, Domino server, Notes client, mobile devices) to maintain stateful applications, to adapt to and work with data from different sources, and so on All such JSF-centric topics are given in-depth treatment in Part II, “XPages Development: First Principles.” Brand New Technology? As already mentioned, the official release of this new-fangled XPages technology took place in January 2009 Given that Notes/Domino was 20 years old that year, this casts XPages as the new kid on the block Therefore, logic should dictate that, given its lack of both absolute and relative longevity, XPages is immature as a development technology and needs a few more release cycles before it “cuts the mustard” in terms of robustness, scalability, and such Correct? Well not so fast On reading on the official history of Notes/Domino recently, it was interesting to note that the provenance of the product itself was not simply traced back to Lotus Notes Release in 1989, but as far back as work done by the founders of Iris Associates on PLATO Notes in the late 1970s! To some extent, similarities exist here with XPages That is, while XPages first surfaced in Notes/Domino version 8.5, a precursor of the technology, called XFaces, appeared a few years earlier in a product called Lotus Component Designer (LCD) LCD was an Eclipse-based integrated development environment that used XFaces to build applications for IBM WebSphere® Application Server (WAS) and IBM WebSphere Portal Server While Lotus Component Designer went into maintenance mode for a variety of reasons, its XFaces runtime technology continued to receive development investment XFaces was seen as a flexible technology that could quickly simplify, modernize, and standardize the Notes/Domino web-application development experience Thus, it was quickly adapted and specialized for the Notes/Domino platform and evolved A Different Development Paradigm into what is now known as XPages In reality, the LCD/XFaces release effectively bought XPages another couple of years of industrial experience, and when one considers that JSF version 1.1 was released in June 2004, maybe XPages is not the pimply adolescent you first took it for! In any event, XPages is here and successfully enjoying its third revision on the Notes/Domino platform In its first release, XPages shipped as part of the Domino server and Domino Designer kits Domino Designer was rebased to run on the Eclipse platform in that same 8.5 release, and with it, the application development experience for Domino web developers was thoroughly transformed The new underlying Eclipse platform meant that an entire host of new tools could be built for or surfaced in Domino Designer The XPages development experience suddenly featured all the tooling that had been requested for Designer in general for many a long day (such as a control and data palette, drag-and-drop components, property sheets, structural page outlines, specialized editors, and so on) A new design element called an XPage, along with a junior sidekick called a custom control, appeared on the navigator, and instances of these could be built up in an intuitive WSYISYG fashion, using a combination of all the aforementioned cool tools Once built, they could be immediately previewed or run directly on the Domino server from a web browser Hmmm, building web applications had never been so easy—there just had to be a catch! A Different Development Paradigm The catch, if you can call it that, is that the XPages development paradigm is different to what Domino web developers were used to up until version 8.5 Here, black magic practices, like $$Return fields and strategically embedded pass-through HTML, are no longer the web dev modus operandi XPages development is driven by combining Cascading Style Sheets (CSS), JavaScript, HTML, and the XSP tag language Although this is no doubt a superior model, and certainly one that is immediately more intuitive to web developers from a non-Domino background, an investment of time and energy in learning the ins and outs of XPages development cannot be avoided The term XPages (plural) usually refers to the entity that is the runtime as a whole In its singular form, an XPage refers to a Notes/Domino design element, just like a traditional form or view It is the basic unit of currency for XPages development Developers create individual XPage elements to present information, accept user input, execute business logic, and then link them to form an end-user application If you look under the covers at an XPage in Domino Designer, you see an XML document comprised of various tags and attributes and, at runtime, the XPages engine in Notes/Domino transforms this XML document into an HMTL page Any developer familiar with JSF will already notice a departure here with XPages The default markup layer for JSF is provided using a technology known as JavaServer Pages (JSP) As indicated previously, this layer in XPages has been replaced with a pure XML markup, which greatly simplifies the programming model In other words, all the visual controls, business logic, and layout information that comprise an XPage are encapsulated in a well-defined, well-formed tag syntax that is easier for developers to work with Even at that, however, this raw XML file is Chapter An Introduction to XPages not the default developer interface Domino Designer provides a design-time visualization of the XPage that the developer can work with interactively by dragging and dropping controls and data objects, setting attributes using simple gestures in property panels, or by simply using direct keyboard input All such activity causes the appropriate XPages XML markup to be generated on behalf of the user The XML markup can be viewed or further modified manually via a specialized XPages source editor in Designer Thus, Designer provides different entry levels for the application developer working at the XPages frontlines Newcomers typically begin by working with the visual XPage canvas and then may start to work more directly with the source markup as they become more familiar with the technology, depending of course on what they are trying to achieve in a given scenario At the end of the day, however, regardless of how it is edited or viewed, it is worth remembering that an XPage is just a text file made up of an orderly bunch of tags! It is also important to realize that any controls defined by these XPages tags are user-interface objects only Associating data with such controls is a separate step that is achieved by explicitly binding a control to a data source object This differs from the traditional Notes/Domino paradigm where display fields and data items are tightly coupled (For example, when a field is created on a form, a data item of the same name is automatically created after a document instance of that form is saved.) This schema-less approach has always been “the Notes way” and is useful for putting an application together quickly, but it also has some serious downsides For example, when data fields are defined purely within a particular form, what happens if and when this data needs to be accessed or updated from somewhere else in the application? It may well be that reusing the same form is not appropriate in that user interface (UI) context Clever use of subforms can alleviate that problem to some degree, but metadata often ends up being duplicated across forms and subforms to get around this issue The problem becomes more egregious when dealing with heavyweight design elements, such as views A view, like a form, contains all the presentation layout details and the content definition in one big blob After a view is defined, it is difficult to customize it for reuse elsewhere in the application Duplicating views to achieve what are often minor UI customizations inevitably results in bloatware It negatively affects the final application by producing a larger NSF footprint, adversely impacting performance, and results in a longer list of design elements that the application developer must then somehow manage As a consequence, separation of presentation and data has been a long requested feature of the Notes/Domino application development community The good news is that, with XPages, this is exactly what you get! XPages controls are typically bound to data contained in Domino documents or views The XPages runtime comes equipped with standard Domino data source objects that automate the data connection and retrieval process, and Domino Designer provides various assistants that simplify the procedure of matching controls with items of metadata Thus, the extra data-binding overhead imposed on the developer is reduced to some simple point-and-click operations at design time This is a small price to pay for the extra design flexibility brought about by decoupling the presentation and data Under this model, for example, a single XPage can work with The More Things Change, the More Things Stay the Same multiple document data sources (such as read/write documents, where the data is defined in more than one form), and XPages view controls can effectively “join” data stored in different Domino views—even across different databases! Part III, “Data Binding,” explores the many and varied details of data binding, but at this stage, it is important to recognize that the XPages data model is fundamentally different to the traditional Notes/Domino model The More Things Change, the More Things Stay the Same Although the previous section stressed some advantages of the new XPages development model, it does not imply that traditional Domino development skills are any less valuable Quite the contrary! For example, if you have already gained experience with the Domino object model by using the LotusScript® or Java backend classes, these skills enormously benefit you in building XPages applications, because a parallel set of JavaScript classes are available in XPages This means that, albeit with a slightly different class nomenclature, the usual suspects, such as Session, Database, and Document, are all present and accounted for when it comes to coding the application business logic Similarly, the time you may have spent learning your Notes/Domino @Functions through the years continues to pay dividends An extensive set of the procedures you already know and love, such as @DbColumn(), @DbLookup(), and so on, have been implemented in the XPages runtime as JavaScript functions and can thus be called directly in any XPage When adding an XPages interface to an existing Notes/Domino application, many existing assets can be automatically leveraged Web agents, for example, can be executed directly from within an XPage; existing design resources, such as stylesheets, images, and JavaScript files, are also consumable, while the forms and views can be used as XPages metadata resources New Horizons XPages support for the Notes client was added in version 8.5.1, which was released in October 2009—or approximately nine months after the initial XPages Domino server release It is a testament to the architecture of the XPages runtime environment that support for a major platform could be added in the course of such a quick-turnaround point release Given the short development runway, the feature scope for XPages in the Notes client (abbreviated to XPiNC for convenience, which is pronounced “x-pink”) was understandably restricted In essence, its main goal was to enable customers to run their new XPages web applications offline For any customer with an existing XPages application, the use case to run locally in the client had just two simple requirements: Create a local replica of your application using standard NSF replication Select a new XPages client launch option in the local replica Of course, a new XPages client application can be created, just like it could be for the web, as long as the client launch option is selected in the Notes client or in Domino Designer With Chapter An Introduction to XPages some opportunistic exceptions, however, in its initial release, the client user experience was, to a large extent, a web user experience Some of the notable exceptions included: • Enabling XPages to fully participate in Composite applications • Providing client-side JavaScript-to-Notes platform services • Conforming with the Notes client security model • Adding support for preemptive document saving • Integrating other client behaviors, such as bookmarking and failover Perhaps the more interesting point is that, thus far in this book, XPages has been described as a web application runtime—quite intentionally; however, as XPages support for the Notes client is enhanced and web technologies become richer, will XPages continue to be defined purely as a web technology or more as a truly portable framework capable of supporting many platforms in an adaptable specialized manner? The authors of this book are betting on the latter! Conclusion This chapter introduced you to XPages at a high and general level It looked at its provenance and history, revisited the initial goals of the technology, provided a broad view of the development paradigm it offers, and took a speculative look at how XPages may evolve in the future Hopefully, you will find it both interesting and useful to have this big-picture context as you prepare to dive headfirst into the voluminous technical details ahead The next step is to get you started with the practical aspects of the technology by installing XPages and Domino Designer and working through some simple examples Let the fun begin! C H A P T E R Getting Everything You Need This chapter provides a guide for getting the software you need to start working with XPages The main tool you need is, of course, Lotus Domino Designer The good news is that this tool is available as a no-charge download today! Downloads, Versions, and Locations This book is based on Domino Designer 8.5.2, so ideally, you need to obtain this version of the product or something more recent, if available Domino Designer can be downloaded from the IBM developerWorks® site (developer.lotus.com) Follow these steps to get the latest Domino Designer release: Navigate to http://developer.lotus.com You are automatically brought to the Lotus section in developerWorks The Lotus Domino Designer no-charge download should be right there, but if it’s not, go to the Downloads area Lotus Domino Designer is listed as one of the no-charge downloads in this section (see Figure 2.1) If you follow the links to download Domino Designer, you are prompted to sign in using your universal IBM user ID If you don’t already have one, you must register first You just need a valid email address to register You can select the language version of the client you want to install Currently, Domino Designer is available in 26 different languages and runs on Windows Vista Ultimate, Windows Ultimate, and Windows XP Professional editions 10 Chapter Getting Everything You Need Before downloading the client, you need to accept the license agreement This agreement allows you to use IBM Lotus Domino Desinger only for the development of applications on an individual system that is not connected to an IBM Lotus Domino Server and to use such applications on the same system on which the Domino Designer is installed An additional license is required to deploy these applications to an IBM Lotus Domino Server Read the license agreement carefully so you are aware of the specific terms for the download you are installing Figure 2.1 Domino Designer no-charge download After you accept the license agreement, you are redirected to a page where you can download IBM Lotus Domino Designer and any fix packs that apply to that version It is strongly recommended that you download and install any available fix packs Your download is approximately 600–700MB Congratulations! You are now in possession of the latest release of IBM Lotus Domino Designer The next step is to install the program Installing Domino Designer The Domino Designer download (and any fix packs) is an executable file Follow these steps to install the program: Client Configuration 11 Launch the executable you downloaded from the developerWorks site This executable unpacks all the files needed to install the program on your machine You can select to have the install files automatically cleaned up after the install completes or keep them around for reuse later You need approximately 2GB of free disk space to perform the install The install wizard guides you through the process of installing Domino Designer You need to specify your name and the location where you want to install the program On the screen where you select the program features you want installed, make sure that the following are selected (at a minimum): a Notes Client b Domino Designer c Composite Application Editor (required for some rich client samples in this book) Select the install option to start the installation of the selected program features When the install completes, two icons appear on your desktop: one for Domino Designer and one for the Notes client Just a few more short steps before you can create your first XPage! Installing Client Fix Packs The download site might list fix packs for the version of Domino Designer you are downloading As the name suggests, a fix pack contains fixes that have been made to the product since it was originally released You are strongly encouraged to download and apply any available fix packs Installing the fix pack couldn’t be simpler: Launch the fix-pack executable you downloaded from the developerWorks site As before, the executable unpacks all the files needed to install the fix pack onto your machine in a location of your choosing, with the option to remove the unpacked files The wizard guides you through the process of installing the Domino Designer fix pack You should not need to provide any settings Client Configuration If you are using the no-charge download version of Domino Designer, you will not be connecting to a Domino server You can follow the majority of exercises in this book without being connected to a Domino server Follow these steps to configure your client: Launch Domino Designer by clicking the icon on your desktop For the user information, fill out your name and unselect the option to connect to a Domino Server You don’t need to configure any of the additional services 12 Chapter Getting Everything You Need When the client configuration completes, you are presented with a welcome screen that provides some useful information about the version of Domino Designer you just installed Restart your computer Quick Tour of Domino Designer When you start Domino Designer, you are presented with a welcome page that provides some useful information about the version you have installed If this is the first time you have used Domino Designer 8.5 or if you are not familiar with Eclipse-based Integrated Development Environments (IDE), the following sidebar provides a brief background on Eclipse A BRIEF HISTORY OF ECLIPSE In the late 1990s, IBM began developing an integrated development environment platform in IBM’s Object Technology International (OTI) labs This later formed the basis of the Eclipse project The main goal was to develop a platform that could be used within IBM for its many IDE projects—and specifically for a new Java IDE IBM recognized that developing a community of third parties who would use and contribute to this new platform was critical to its success So, in November 2001, this new platform and the associated Java tooling was used to seed the Eclipse open source project, and the Eclipse consortium was founded Since its inception, Eclipse.org has experienced huge success and rapid growth IBM has been developing Eclipse-based product offerings for 10 years now, and the platform has evolved to include not only IDE products but also end-user products Both IBM Lotus Sametime and Notes are now Eclipse Rich Client Platform (RCP) applications RCP is an Eclipse platform for building end-user desktop applications As Eclipse evolved, its IDE-specific parts were abstracted out to provide a generic windowing framework that could be used to create general-purpose applications A great advantage of RCP is that the GUI end product is native to the particular target platform, be it Windows, Linux, or MAC What does it mean that Domino Designer is now an Eclipse-based product? • If you are not familiar with Eclipse-based tools, you need to familiarize yourself with the basic concepts, such as perspectives, editors, and views (nothing to with Notes views) Visit www.eclipse.org for more information The URL http:/ /eclipsetutorial.sourceforge.net/workbench.html takes you to a tutorial that teaches you how to use the features of the Eclipse workbench • Eclipse is a highly productive environment to work in, largely because there are so many add-ons available that allow the developer to customize his work environment to exactly meet his needs Quick Tour of Domino Designer 13 • Existing Eclipse-based tooling (such as Java source editors) now becomes available directly within Domino Designer • Because of its open source heritage, Eclipse is widely used in academia, particularly in the fields of computer science and information technology Consequently, lots of new and recent graduates are already familiar with using Eclipse-based IDEs • Eclipse provides Domino developers with the opportunity to extend Domino Designer in ways that have never been possible In Chapter 12, “XPages Extens bility,” you see that XPages provides similar possibilities for the runtime Whichever way you look at it, taking a popular development tool with a 20-year history and a unique set of development artifacts and moving it to a new Java-based IDE platform has got to be a risky proposition, right? If the approach was to rewrite all the existing tools (for example, editors for Forms, Views, and so on), the answer is a most definite yes In release 8.5, the Domino Designer team took to the approach of hosting some of the preexisting Domino Designer tools (such as the Form and View editors) within the Eclipse IDE and developing brand new native Eclipse tooling (such as the new JavaScript editor) So, for most traditional Domino design elements, it was business as usual insofar as the design-time experience remained the same This is also the approach that was adopted and proven in moving the Notes Client to the Eclipse RCP; however, that’s only the first part of the story In addition to having all the old tools without the risk of a rewrite, developers now have lots of new stuff (such as new editors for style sheets, Java, and JavaScript) All the tools for XPages were developed specifically for Eclipse and, as such, take full advantage of the platform The new Domino Designer also includes a virtual file system that allows Eclipses to view an NSF file as a hierarchical collection of files I’ve been using Eclipse for many years, but I’m still learning new things all the time When I sit with a colleague to some pair programming, I often find that he has a slightly different way of doing something or a cool shortcut that I haven’t seen We share our favorite tips with you throughout this book Domino Designer Welcome Screen When you launch Domino Designer, you are presented with the Welcome screen (see Figure 2.2) This book is being written as Domino Designer 8.5.2 is being developed, so if you have installed a later version, there might be some information on the Welcome screen about other cool new features You probably don’t want to always see the Welcome screen every time you start, so you can uncheck the option to always show at startup To dismiss the Welcome screen, click the Close button in the top corner 14 Figure 2.2 Chapter Getting Everything You Need Domino Designer Welcome screen Domino Designer Perspective The Domino Designer perspective is where you the majority of your work, as shown in Figure 2.3 This provides a Domino-centric view on all the projects that you have open The Application Navigator lists all the Domino applications you are working on Start by creating a new application and creating your first XPage The Domino Designer home page provides a shortcut that allows you to quickly create a new application In the event that you get lost in Eclipse, and it can happen when you start to explore, you can always get back to the Domino Designer perspective by using Window > Open Perspective > Domino Designer You can also reset your Domino Designer perspective to the defaults by using Window > Reset Perspective Quick Tour of Domino Designer Application Navigator Figure 2.3 15 Home Window Domino Designer Perspective with the Home window Creating a New Application Following the time honored tradition, your first step is to create a “Hello World” application Here are the steps to create a new application: Choose File > New > Application In the New Application dialog (see Figure 2.4), enter the filename of the application (for example, HelloWorld.nsf) and choose OK A new application is created and appears in the Applications navigator (see Figure 2.5 in the next section) 16 Chapter Figure 2.4 Getting Everything You Need New Application dialog Creating an XPage Next, create your first XPage design element: Choose File > New > XPage In the New XPage dialog, enter the name for the XPage (for example, home) and choose OK Type the text “Hello World” into the new XPage Editor Panel and save the XPage After you create and open an XPage design element, the Domino perspective fills with all the appropriate tools for you to work on that design element, as shown in Figure 2.5 The default tools that are provided are as follows: • XPages Design Elements: All the application XPages design elements are listed here Double-click the XPages entry in the Designer Database Navigator to bring up the XPages design list This lists all the application XPages and some summary information about each item • XPages Editor: An XPages-specific editor supports two modes of operation: • The default mode of operation is visual editing; that is, you can type directly in the editor to add text, drag-and-drop new controls into the editor, and change the attributes of the page or elements within the page using the property panels • Source-mode editing is also provided; each XPage is just an XML file and, in source mode, you can directly edit the tags Quick Tour of Domino Designer 17 XPages Design Elements Controls Palette XPages Editor Property Sheets Outline Figure 2.5 XPages Editor • Controls Palette: Lists all the standard user interface controls that you can add to an XPage to create your application user interface This palette automatically gets extended with any custom controls you create Custom controls are explained in Chapter 10, “Custom Controls.” • Property Sheets: Contain tabs for the selected item’s Properties, Events, and Problems: • The Properties tab allows you to visually configure the properties for the currently selected item (for example, the XPage or a selected item within the page) • The Events tab lists all the events for the currently selected item and allows you to add business logic, which executes when that event is triggered • The Problems tab lists any errors or warnings for the current XPage • Outline: Provides a hierarchical outline that shows all the elements in the current XPage • Data: Shows all the data sources associated with the current XPage and allows you to define new data sources (not shown in Figure 2.5) Data sources are covered in more detail in Chapters and 18 Chapter Getting Everything You Need The “Hello World” application is complete The next step is to run it and see it working Domino Designer provides options to preview an XPage in the Notes Client or a web browser Previewing in the Notes Client Previewing an XPage design element in the Notes Client couldn’t be simpler: Choose Design > Preview in Notes The Notes Client starts and the XPage is displayed, as shown in Figure 2.6 TIP The Preview in Notes option is available in the context menu when you right-click in an XPage design element It’s also available on the toolbar under the Design top-level menu, and by right-clicking the XPage in the navigator Figure 2.6 XPages Preview in Notes Previewing in a Web Browser If you try to preview the XPage in a web browser, you see the following error message: To successfully preview this element in a Web Browser, please add (or modify) the ACL entry for Anonymous (or the default ACL) to have at least Author access with the ability to create documents Quick Tour of Domino Designer 19 The security aspects of Notes and Domino are covered in depth later in this book; however, for now, it suffices to say that access to every application is controlled using an access control list (ACL) By default, anonymous access is prevented, but this is the access level used when previewing a local application for the web Here is how you allow anonymous access to the Notes application: Choose File > Application > Access Control The Default entry is selected in the Access Control List Change the Access level from No Access to Author Select the option to Create documents (see Figure 2.7) and choose OK Figure 2.7 ACL for the Hello World application Now the application is configured to allow you to preview in a web browser The next step is to configure your application to use the XPage that you just created as the design element when the application is launched: Choose File > Application > Properties Choose the Launch tab Under Web Browser Launch, select Open designated XPage from the Launch dropdown 20 Chapter Getting Everything You Need Select the home XPage from the list the XPage drop-down, as shown in Figure 2.8 XPage home configured for Web Browser launch Figure 2.8 Web browser Launch Properties Choose File > Save to apply these new application properties Choose Design > Preview in Web Browser > Select either of the default browsers as specific browser to use when previewing Your preferred web browser starts and the XPage appears, as shown in Figure 2.9 Figure 2.9 XPage Preview in a web browser Preview in Notes and the web browser dynamically updates in response to changes in the XPage being previewed You can see this working by going back to Domino Designer, changing and saving the XPage, and then going back and hitting the Refresh button in the Notes Client or web browser Your changes are updated immediately in the preview Quick Tour of Domino Designer 21 So far, you’ve seen how easy it is to create the basic “Hello World” application and preview your work Next, you complete this application by adding a customized greeting Adding a Control to an XPage You now change “World” to a Computed Field (possible theme song for this book): Delete the text “Hello World” from the home XPage Drag-and-drop a Computed Field from the Controls palette to the XPage In the Properties sheet, choose the Value tab Select JavaScript as the Bind data using option Enter the following JavaScript and save the XPage (see Figure 2.10): ”Hello “ + context.getUser().getFullName() Edit the Value for the Computed Field Figure 2.10 Adding a Computed Field You just added a control that computes its value, and you configured it to retrieve the common name of the current user and prefixed this with the static text “Hello.” Chapter 6, “Building XPages Business Logic,” covers data binding and the JavaScript classes in more detail You should now preview this XPage again 22 Chapter Getting Everything You Need As you saw earlier when previewing in a web browser, anonymous access is used So, it’s no surprise how the greeting appears in the browser preview (see Figure 2.11) Figure 2.11 Preview in a web browser TIP Change the computed expression to ”Hello “+session.getCommonUserName() and you get a proper username when previewing in a web browser If you repeat the Notes Client preview, you see that the name comes from the Notes ID that was used when you logged into Domino Designer (see Figure 2.12) TIP If you are using the no-charge download, you may see “Hello null” when you this test This is because the full name may not be set on the Notes user ID that was created Figure 2.12 Preview in Notes You can refer to Appendix C, “Useful XPages Sites on the Net,” for some useful resources to help supplement your skills and understanding of developing in Lotus Domino Designer Congratulations! You are now up and running with XPages development Conclusion Now you have everything you need to start exploring the world of XPages There is a sample Notes application associated with each chapter of the book, which includes the XPages discussed in the chapter (you can access these files at www.ibmpressbooks.com/title/9780132486316) The best way to get the most from this book is to follow along with the samples in Domino Designer In the next chapter, you will build your first XPages application C H A P T E R Building Your First XPages Application Now that the setup details are squared away, it’s time to roll up your sleeves and start some realworld XPages application development Development technologies are best absorbed by working through practical examples and solving everyday concrete problems For this, you need a reference application to work with, and the standard Notes Discussion template is an ideal candidate Pretty much all the topics covered in this book are already implemented in one way or another in the Discussion template, and you will disassemble and rebuild this application as a way of developing your XPages expertise! This is also convenient for you insofar as the Discussion template ships out-of-the-box with Domino Designer, so you automatically obtained this application template as part of the installation work performed in Chapter 2, “Getting Everything You Need.” A different instance of the reference application is provided for each chapter Be sure to download these resources so that you can work through the exercises in Domino Designer according as you read your way through this book This will undoubtedly be the most effective approach from a learning point of view Typically, the name of a given reference application instance is derived from the chapter with which it is associated For example, for this chapter, open Chapter3.nsf in Designer The nsf resources can be downloaded from this website: www.ibmpressbooks.com/title/9780132486316 This chapter provides a general breadth of information covering both Designer and XPages It gets you accustomed to building simple XPages that read and write Notes data and implement standard application features In summary, you will learn the following: • How to define application metadata using forms and views • How Notes stores real app data using documents and views • How XPages can access that data for reading and writing 23 24 Chapter Building Your First XPages Application • How XPages can be linked to form a cohesive entity • How to implement simple business logic without writing any code This is an ambitious undertaking for one chapter! Obviously, some details will need to be glossed over to achieve this goal in such a short time, but any such details will be explored in depth in the remainder of this book Laying the Foundations You should start by creating an instance of the Discussion application and play around with it to get a feel for its features and functionality As you learned in the previous chapter, you can create a new application by simply selecting the File > New main menu option or type Control-N in your Designer workspace Many application templates are shipped with Notes (mail, discussion, doc library, and so on), and you should select discussion8.ntf to create your new application based on the latest Discussion design Figure 3.1 shows all the relevant selections Figure 3.1 Creating a new Discussion application in Domino Designer To experiment with the application, simply open its main page, allDocuments.xsp, and choose to preview it using a web browser or the Notes client To enable web preview, you need to tweak the application’s access control list (ACL), as you learned in Chapter To save yourself some time, you should also enable the Anonymous user to delete documents, because you will need this capability for a later exercise Once opened in preview mode, the application is fully Laying the Foundations 25 functional, so you can create new documents, categorize them into different groupings, navigate between different views, and so on Figure 3.2 outlines the anatomy of a Discussion application populated with some sample data Actions App Navigator Author Cloud Figure 3.2 Toolbar View Pager Full Text Search Tag Cloud Categorized View Sample Discussion application and its component parts As you explore the template more fully over the course of this book, you will discover that it is a feature-rich Web 2.0 application, making full use of Ajax, Dojo, JavaScript, and Cascading Style Sheets (CSS) This is what makes it so useful as a learning vehicle At this point, however, you might need to start with the basics, such as learning how documents are defined, created, and stored in an application Figure 3.3 shows a sample new topic under composition in the XPages Discussion app At this point, you can use the New Topic button to create some sample documents The text you enter in the Subject field is displayed in the summary document view, the Tags field categorizes your documents (it supports multiple categories if you use comma-separated entries), and the third field is the main document body and is fully rich-text enabled When you enter data in all three fields, click Save to store the document As you navigate around the application, you can also edit and delete these documents Doing so gives you a feel for the application’s features and behaviors 26 Chapter Building Your First XPages Application A cursory glance at Figure 3.3 tells you that any new document, from a data standpoint, must contain at least three data items: say Subject, Categories, and Body For those of you new to XPages and Notes, the question is how and where these data items are defined Figure 3.3 Sample topic document Save the sample document shown here, because it is used in the upcoming exercises Forms and Views Although you have just been playing with the Discussion template as an XPages application, it is also, of course, a native Notes application that runs independently of XPages in the client In fact, the XPages interface was only added to the template in version 8.5, while the Discussion app itself was first introduced over a decade before that! The original Discussion application was built using traditional Domino design elements, such as forms and views To see the native application in operation, simply expand the Forms entry in the Designer navigator, double-click the Main Topic form to open it, and perform a client design preview using the same Preview toolbar button used when previewing any XPage After the form loads, enter some text Compare the XPage interface shown in Figure 3.3 to the classic form shown in Figure 3.4—different renderings but the same data! For the purpose of the exercises in this chapter, there is no need to save the document shown here Return to Designer and, this time, open the Views entry in the navigator (It is recommended that you work your way through this chapter and actually perform the various tasks in Designer while you read them here.) Locate and select the All Documents view in the navigator Forms and Views Figure 3.4 27 Preview of the Main Topic form and click the Preview in Notes toolbar button When the view opens in the client, you see that the document you just created is presented Now, you should reopen the sample document, rightclick anywhere in the view window, and select Document Properties from the context menu A nonmodal floating dialog box, commonly known as an infobox in Notes/Domino, is presented, and this can inspect the data stored within the document Choose the second (Fields) tab on the infobox and click any of the fields presented in the listbox As you so, the data stored in those fields is displayed in the adjacent text box—for example, the XPages category text appears to be stored in a WebCategories field, as shown in Figure 3.5 Figure 3.5 Infobox listing the field properties of a sample Notes document All the fields you see listed in the infobox are defined using a form design element In Notes, a document is simply an instance of a form All the fields or items defined on any given form can be assigned values after a document is composed and then saved For traditional Notes applications, the form design element is the container for the both the metadata (for example, data design and structure definitions) and the user interface (controls, layout, and so on) The key point for you to understand is that an XPage allows you to create a Notes document based on the metadata defined within a form, but entirely ignores the form’s presentation layer In other words, XPages gets the data definition of any given document directly from one or more forms, but provides its own user interface and business logic 28 Chapter Building Your First XPages Application Reopen the Main Topic form in Designer Figure 3.6 shows the three fields mentioned earlier as defined within the form All the other UI artifacts you see are irrelevant to XPages As you start to build new XPages apps from scratch, you will still need to create forms to define the application metadata, but these will be much smaller than the traditional Notes form definitions you see here, because no UI or business logic will be stored in them In other words, think of these Notes forms as comprising the database schema for your XPages application Data fields Figure 3.6 Field definitions in Main Topic form From an XPages perspective, there is not a lot to learn about form design because XPages only really uses them as metadata containers On any form, you simply use the Create > Field option on the main menu to add a field and then enter the name and data type via the infobox Figure 3.7 shows a sample field infobox The types displayed in Figure 3.7 are interesting, because they appear to represent a mixture of data and presentation concepts It is easy to think of the first three types (Text, Date/Time, Number) purely in data terms; however, many of other types are usually thought of only as UI widgets, rather than as data types per se (for example, Radio button, Listbox, and Combobox) For example, if a field is defined as a Radio button in Notes, what type of data is stored in the document when the user makes a selection at runtime? The answer is perhaps not clear cut If you are working with forms designed by other developers (such as a legacy application that you inherited), it is always useful to inspect some document instances using the infobox and reconcile the metadata definitions with the actual document field data Note that other important fields are created and stored automatically by Notes, over and above those that are explicitly defined in an application’s forms Every document, for example, automatically contains a document ID and unique ID (UNID) These items will prove useful in your development tasks later on, and examples of these fields are shown in Figure 3.8 Forms and Views Figure 3.7 29 Inspecting field definitions in Designer Document UNID Date of Revision Document Note ID Database Replica ID Figure 3.8 Document IDs in the infobox TIP Other tools are available to inspect Notes data A long-time favorite in the community is Notespeek, which provides an explorer-like interface for NSF files and the elements contained within them This utility can be downloaded from an IBM developerWorks sandbox site—simply search for Notespeek on the Internet Although the form design element is used to define the content of a document, the view design element is what Notes uses to manage collections of documents A Notes view presents summary data for a collection of documents, and the documents included in the collection are chosen using some type of selection query Explore some of the many views in the Discussion template You see that they all contain a View Selection query For example, Figure 3.9 shows the ($xpCategorized) view in design mode, including a simple Notes formula language query: SELECT (form = “Main Topic”) 30 Chapter Building Your First XPages Application Refresh View Selection Formula Figure 3.9 Column Properties View design Basically, every Notes document is automatically assigned a Form field that identifies the form used to compose it, and this particular view includes all documents contained within the NSF that were created using the Main Topic form The view itself is comprised of an array of columns A column can simply be the name of a field contained in the selected documents or a computed value The top-left corner of the view contains a Refresh button that allows you to populate the view at design time, which comes in handy if you are building a view from scratch and want to periodically validate your content Again, for Notes/Domino neophytes, there’s not a lot to figure out with Notes view design—certainly at this basic level New view instances are typically created using the helper dialog invoked from the Create > Design > View menu or by copying and modifying an existing view of a similar design to what you want Columns are added to a view via the main menu or view context menu, and configured using the infobox—just like fields in a form The form and view you will work with in this chapter already exist, namely Main Topic and All Documents, respectively Thus, at this juncture, there is no need to delve any deeper into how these elements are created The key thing to understand is that XPages uses a Notes view to work with a document collection Again, XPages is not interested in the presentational aspect of the Notes view, but just its content The presentation of the view data is performed by XPages; this concept will become c learer when you build a sample view in the next section Building an XPages View 31 TIP If you are new to the Notes/Domino document-centric data model, but understand the basic relational data model, the following analogy might add clarity Think of the documents as records, the document items as fields, and the views as tables In any case, it’s time to create some new XPages and put what you just learned about Notes forms, documents, and views to good use! Building an XPages View The Discussion template offers the user numerous ways to view the documents contained in the application (for example, By Author, By Tag, and so on) In this section, you learn to build a view just like these To jump in, create a new XPage, call it myView, accept all other dialog default values, and click OK Start by finding the View control within the Container Controls section of the Controls palette and dropping it anywhere on the blank page (aesthetics are not important at this point) Figure 3.10 identifies the required control for you Figure 3.10 View control in Container Controls palette As the drag-and-drop gesture is executed, Designer presents a helper dialog that allows you to bind this XPages View control to a Notes/Domino view data source Confused? Hope not— this is where you bind the XPages UI View control to the backend Domino view data (remember the concept of presentation/data separation previously discussed) The View control picked from the palette is the presentation layer object that will display data, and you can bind it to the Notes All Documents view, which contains the actual data Figure 3.11 shows the binding dialog 32 Chapter Building Your First XPages Application App Browser View Picker Column Picker Figure 3.11 View data binding helper dialog After All Documents is selected, a list of its constituent columns are dynamically retrieved and displayed Thus, you are not compelled to select all columns from the Notes view chosen as the data source If you not want to display a particular column in your XPage, simply deselect it by unchecking the checkbox that is located alongside its name To keep it simple in this instance, select just two columns—Date and Topic—and click OK The result is perhaps surprising! I think you’ll agree that this helper dialog has done a lot of work on your behalf A View control has been defined on the XPage based on the dialog choices provided, and some default settings have been applied, such as the maximum number of rows to display in the View control at any one time (30 by default) Domino Designer provides at least three interesting ways to look at the View control Obviously, there is the WYSIWYG design pane representation, which gives a rough sketch of how the view will look at runtime Then, there is the outline viewer, which may be more instructive in this instance The fully expanded outline shown in the bottom-left corner of Figure 3.12 encapsulates the hierarchical structure of the control that’s been created You can see that the View control has many parts, including a default pager wrapped up in something called a facet (more on facets in Part II, “XPages Development: First Principles”), a view data source reference, and two columns, each of which contain header elements The full markup is also available in the Source pane and included in Listing 3.1 Building an XPages View 33 Design-Time Rendering Hierarchical View Structure Figure 3.12 Listing 3.1 View Data Source Details View drag-and-drop results View Control XSP Markup With the possible exception of the pager element, which will be expanded on in later sections, it can be reasonably argued that the markup semantics are self-explanatory—for the most part, just a descriptive summary of the information collected in the data binding helper dialog Save the page and then, when you preview it, you will see that the correct summary data is now displayed in your view, as shown in Figure 3.13 Note that the empty parentheses in the Topic column entry would normally display the name of the document author This document has been created using Anonymous access and, for simplicity, the XPage did not create a From field in the underlying Main Topic form, so no author information is available for display You learn how to compute and save an author field in the section, “Executing Form Logic” in Chapter 7, “Working with Domino Documents.” Figure 3.13 View control preview So far, so good, but how you work directly with individual documents as opposed to viewing document collections? To this, you need another XPage Call this new XPage myTopic, because it will be used to create, read, and edit documents created using the Main Topic form The first thing you in this new XPage is create a new document data source Again, this is a simple point-and-click procedure: Select the Data property sheet on the new blank XPage Choose Domino Document from the Add drop-down button In the Form combo box, select the Main Topic form This is all you need to to create a new basic document data source There are, of course, a host of other options that can be used to configure the data source (see Chapter for all the details), but simply nominating a form is sufficient to gain access to all of its metadata, and that’s all you need to at this stage Building an XPages View 35 TIP From Notes/Domino version 8.5.1 onward, you can create the Domino document data source while creating the XPage There is a new option on the New XPage dialog to add the data source at the same time This is a useful shortcut The contents of the document data source (all the fields defined in the Main Topic form) can be viewed by activating the Data palette, which is the tab adjacent to the Controls palette in the top right of the Designer perspective You will see many fields listed there, but you are just interested in three of them: Subject, WebCategories, and Body These fields can be selected by control-clicking each member, and then dragging the fields to the blank XPage, which again saves you a lot of work Figure 3.14 should closely match your results Save the XPage and preview it to see how it looks at runtime Auto-generated page contents Link to Data Palette Data Source field list Data source definition Figure 3.14 Document drag-and-drop results Now for the missing link—quite literally! It would be natural in any view to be able to open one of its entries by simply clicking it The view control supports this feature in a simple way Track back to the myView XPage and select the View property sheet There is a combo box with the label “At runtime, open selected document using:”, and here is where you can bridge myView to myTopic by simply selecting the latter as the target XPage 36 Chapter Building Your First XPages Application After you mark the View control column as a link column, XPages opens the associated document using myTopic.xsp when the column entry is selected by an end user at runtime So, to finish this task, select the Topic column in the View control and move to the Display property sheet This property sheet provides the option to wrap the column’s data as an HTML link, so check the appropriate checkbox, as shown in Figure 3.15 Active View Control Column Enables user to select row entries Column content will be presented as a link Figure 3.15 Display view column as link property It’s save and preview time again—as long you’re making progress, you’ll never tire of this feature! This time, your XPage renders the “Hello XPagers!” text as a link, and following this link opens the XPage that contains all the full document details Here, you can read and edit the details You could even save your changes if the XPage allowed you to, and navigate back to the original XPage Hmmm I guess it’s obvious what needs to be done next! Completing the CRUD Most any application you have ever used is required to create, read, update, and delete records—or perform CRUD operations, as it is commonly known To fully support CRUD operations in the current example, there are a few things left to Completing the CRUD 37 First, myTopic.xsp needs a way to save new or edited documents, or cancel such edits and navigate back to the view Second, you need to enable the user to create new documents and delete existing documents You can this by adding actions to myView.xsp Start with myTopic The drag-and-drop action of the Domino document data source in myTopic neatly wrapped all the generated controls into a HTML table Select a table cell in the bottom row of the table presented in the Design pane and use the main menu Table > Append Row(s) option to add a new row to the bottom of the table Then, drag-and-drop a Button from the Control palette into each table cell These will become your save and cancel actions Start by clicking the left-hand button and changing its label text to “Save” in the Button property sheet Immediately adjacent to this label is an Options group box that, among other things, allows the button type to be set Make this a Submit button This simply means that, when this button is clicked, the entire page is submitted to the server, and once that occurs, any data sources contained therein will be saved (assuming no validation failures) Thus, in this case, there is no need to perform an explicit document save operation Simply designating the button to be of type Submit means that this happens automatically (see Figure 3.16) Nice! Active Button Button Type Options Figure 3.16 Adding action buttons Taking care of the cancel action is even easier Again, you must first change the label, although this time, let’s it a little differently to show off another Designer feature When you select the second Button control, hit function key F2 on your keyboard; this allows you to change 38 Chapter Building Your First XPages Application the label using in-place editing (for example, you can type the new text directly into the control) This update is immediately reflected in the property sheet and, on the same sheet, you should set the Button type to Cancel Save your sheet and view the markup generated for these two controls in the source pane If all goes well, your source-code snippet should be identical to Listing 3.2 Listing 3.2 XSP Button Markup Although you are not required in this chapter to directly enter any XSP markup in the Source pane, it is nevertheless interesting to see what is automatically generated by selecting a few simple UI options The event handlers you see here define the runtime behavior that occurs when the buttons are clicked Ignoring some of the more subtle attributes for the moment, you can see that the first button requests a save and the second button does not TIP If you don’t like the way some tags are autoformatted in the source pane window, you can quickly reformat or “pretty print” the tags in question by highlighting them with the mouse and typing Control-Shift-F on your keyboard Try it! Completing the CRUD 39 The last thing you need to with myTopic.xsp is to define some simple navigation rules to control where the user ends up after these actions are performed The XPage itself has Next Page properties that you can use Simply click anywhere outside the main table so that the XPage itself becomes the selected object, or select the XPage root node in the Outline pane and choose myView from the Next Page combo boxes on the property sheet, as shown in Figure 3.17 Thus, the user returns to myView after the myTopic is submitted In fact, in Figure 3.17, the myView page navigation is also selected in the case where there is an update failure, so you will end up in myView.xsp one way or another XPage Navigation Pickers Figure 3.17 XPage navigation properties The second part of your current task is to revisit myView.xsp and introduce CREATE and DELETE operations After the myView XPage is activated in Designer, add two new Button controls anywhere on the page Being a dab hand with buttons at this stage, you can quickly change their titles to “New Topic” and “Delete Selected Document(s),” respectively Once complete, use what are known as Simple Actions to execute the operations To create a new topic document, select the Button on the Design pane and activate the Events tab that is located alongside the Properties tab Front and central on this property sheet is an Add Action button Assuming that Simple Actions is the currently selected action type (it is by default), click this button and you see the helper dialog presented in Figure 3.18 In summary, the steps are as follows: Select the New Topic button Activate the Events tab Be sure that both the onclick event and Server tab are selected Click the Add Action button to launch the Simple Action helper dialog Choose the Open Page as your action Choose New Document as the target document Click OK to complete the operation 40 Chapter Building Your First XPages Application Simple Action for Button Action Button Events Panel Simple Action event trigger Figure 3.18 Add Simple Action dialog: open page You not need to enter or compute a document ID in the helper dialog because your action is creating a new document, so the ID is automatically created by Notes at runtime If you were using this simple action to open an existing document, you would need to provide an identifier In later chapters, you will see examples of how these IDs can be obtained programmatically Similarly, with the second button, you need to add another simple action This time, it is a Delete Selected Documents action, and it’s safe to say that, as a best practice, you need to add some text to warn the user that this action will remove data from the database! Figure 3.19 summarizes this task Be aware that the action needs at least one row to be selected to have something to act on (that is, the user must have the capability of identifying the document to be deleted) In order for rows in a view to be selectable in the first place, each view row needs to display a checkbox that enables the end user to make the necessary selection This checkbox is not displayed by default, but it can be enabled via the same property sheet shown in Figure 3.15 Yes, you guessed it—it’s the checkbox property called Check box Select this option for the first column (Date) in the view control All that remains is to preview the myView page to verify that everything works as intended You should now be able to carry out a full CRUD operation in preview mode Test this scenario as follows: Completing the CRUD Figure 3.19 41 Add Simple Action dialog: delete selected documents Use the New Topic button to create a new “throw away” document Enter some arbitrary details and click Save Once returned to the view, click the link to your new document and edit its details Save your modifications and verify that those changes are saved Once returned to the view for the last time, select the checkbox for the newly created document and click Delete Selected Document(s) Verify that a warning dialog is presented (see Figure 3.20) Click OK to proceed Verify that your new “throw away” document has indeed been thrown away, meaning that it is no longer displayed in the view (it has been deleted from the NSF) Figure 3.20 Confirmation dialog for Delete Selected Documents action 42 Chapter Building Your First XPages Application If all the preceding steps execute as described, then congratulations are justifiably in order, as you have succeeded in building a functional XPages CRUD application in no time at all You have followed the same basic procedures that are used in the template itself, although these would not be clearly evident to you at this stage because the real XPages contain so many other features In having walked through this scenario in the course of umpteen XPages demonstrations, this author can assure you that this whole CRUD app dev scenario can be completed from scratch in about ten minutes Rapid application development indeed! Conclusion Although you made great progress in a short time, there’s obviously a long way to go with building the XPages applications Remember that this chapter gave you some breadth on XPages application development—all the depth comes later You learned to build a basic view similar to those you see in the standard Discussion template You learned to perform CRUD operations on Notes documents using only point-and-click operations You linked XPages to create an application flow, and you implemented simple business logic without writing a line of code Going forward, clearly more advanced features need to be added; for example, input validations need to be applied to manage end-user data entry, rich objects need to be handled, uploading and downloading must be supported, security enforced, a sleeker and more dynamic user interface built, yada, yada, yada! You will all those things and more over the course of this book TIP If you are new to XPages and want to work on other introductory examples before continuing, study the XPages Site Finder tutorial under Lotus Domino Designer User Guide in Designer Help Now that you have gotten your feet wet in XPages application development, it is perhaps the most appropriate time to take a brief sojourn from the Discussion template, and instead take a more holistic look at the technology that underpins what you have just built Part II, therefore, provides an architectural view of XPages, which hopefully will prove all the more meaningful now that you have done some introductory practical work with the technology here in Part I Thus armed with both experience and deeper understanding, you will return to hands-on XPages application development in Part III You will dive deeply into the great spread of XPages features and look at how they can be applied when building more sophisticated application solutions Sound like a plan? PART II XPages Development: First Principles Anatomy of an XPage 45 XPages and JavaServer Faces 129 Building XPages Business Logic 157 43 This page intentionally left blank C H A P T E R Anatomy of an XPage Several years ago, I participated in a study that set out to identify steps to help increase the use of Eclipse in universities and colleges around the world One aspect of the study involved conducting a series of interviews with lecturers of computer and information technology–related courses During the interviews, I heard the same message being repeated, and it was something that initially took me by surprise Most lecturers actively discouraged or even disallowed the use of Integrated Development Environments (IDEs) when teaching a programming language course For example, when teaching Java, a common practice was to have students write their code in a plain text editor and then compile and run it from the command line The value in this approach was that students learned the fundamentals of the language (how to write code without the benefit of content assistance and other tools that would help them write code and prevent them from making obvious mistakes) This is the primary reason that this chapter is important to you: You will learn to create an XPage by hand so that you understand what is actually happening under the covers to an XPage when you use Designer You might even find that you prefer to create XPages this way More importantly, you won’t be bound to the editors and wizards of Designer Depending on your preference and\or the task you are performing, you can switch between visual and source code editing In particular, when you need to modify an existing XPage, using the source mode allows you to see the full page in one go and can be quicker than navigating through the relevant editors That said, using Designer’s editors and properties panels typically remains the fastest way to create an XPage for even experienced developers In the real world, professional developers need tools to help increase their productivity and make performing simple, routine tasks quick and easy However, there is one drawback with using a graphical editor tool: It can be difficult to understand how an XPage actually works If you weren’t the person who created a particular 45 46 Chapter Anatomy of an XPage XPage, it’s often difficult to quickly understand what the XPage is doing and where the business logic is embedded This is because the XPage, as presented in the graphical editor, can be dramatically different from what is presented at runtime, especially when there is heavy use of custom controls and Cascading Style Sheets The XPage graphical editor has some great features to help you see where the business logic is specified (such as the computed diamond to overview all properties of a particular element in the page or within the All Properties view) Although you can everything with the WYSIWYG editor in Designer, an important skill to develop is the ability to read and understand the markup of an actual XPage This is the secondary reason that this chapter is important to you: You will learn how to read the XPage source (XSP markup) and understand how the different elements work together at runtime This chapter teaches you to write and read XSP markup and helps you understand the first principles of the XPages programming model This chapter is written to allow you to skim for now if you are happy to rely on the graphical editor and to come back later to dive into particular concepts as they get introduced This chapter contains many sample XPages that demonstrate different syntaxes and the behavior of different tags To get the most out of this chapter, preview each sample so you can see how they behave and experiment by modifying the samples You can use these samples as a source of snippets of XSP markup for reuse within your own applications With these thoughts in mind, let’s dispense with the WYSIWYG editor in Designer and work primarily in the Source editor Even when working in source mode, the graphical tools are useful for inspecting the properties of a tag you are editing or providing a starting point when creating the user interface Be sure to download the chapter4.nsf file provided online for this book to run through the exercises throughout the chapter You can access these files at www.ibmpressbooks com/title/9780132486316 What Exactly Is an XPage? The definition of an XPage will grow the more you learn about the XPages programming model For now, an XPage is A Notes database design element that is used to present content in either a web browser or the Notes client Each Notes database design element performs a specific job, such as a Notes Form is used to create, edit, and view Notes documents, and a Notes View is used to view collections of Notes documents An XPage is a powerful Notes design element because it can the same types of content presentation that a Notes Form and a Notes View can do—and more Also, the XPages programming model supports the capability to use XPages to extend itself Later in this book, you see that a special kind of XPage can be created, called a Custom Control, which allows you to extend the set of controls available for use in your applications This is a powerful concept; if you need to extend XPages, firstly you can so easily, and secondly, you don’t need to learn something new to it Understanding XSP Tag Markup 47 You will learn more about the architectural heritage of the XPages programming model later in Chapter 5, “XPages and Java Server Faces,” and this will increase your understanding of XPages’ capabilities Understanding XSP Tag Markup XPages uses XML as its file format The XPages XML syntax is called XSP (this ancronym doesn’t stand for anything) If you are new to XML, we strongly urge you to read one of the many XML primers available on the Internet or, if you’re feeling brave, look at the specification (www w3.org/XML/) For now, the following XML primer provides the basics Getting Started with XML XML is a text-based data format that has been defined by the World Wide Web Consortium (W3C) It is widely used for many applications, including electronic publishing, data exchange, document file formats, and more The primary characteristics of XML are • XML is a markup language and similar to HTML • XML is a standard widely used in the industry • XML is a general-purpose data format with strict rules in how the data is formatted • XML does not include any definition of tags HTML is probably the most widely known markup language; however, HTML differs from XML in the last two points in the preceding list First, the formatting of HTML is not strict, and web browsers still render HTML that doesn’t have properly terminated tags or properly defined attributes Listing 4.1 shows an example of some badly formed HTML that will nevertheless work in a browser In this example, notice that the tags are not properly terminated and the attribute is not inside quotes This is one of the strengths of HTML—it’s easy for anyone to create an HTML page that displays correctly Listing 4.1 Sample HTML First Cell Second Cell By contrast, XML must be well formed, which means that, at a minimum, all tags must be properly terminated and all attributes correctly defined So, taking the same example, to be wellformed XML, it must look like Listing 4.2 48 Chapter Listing 4.2 Anatomy of an XPage Sample XML First Cell Second Cell XML is general purpose and does not define any tags Instead, XML can be used as the basis for the definition of many different languages The language definition has its own rules; these rules can be defined in a Document Type Definition (DTD) or an XML schema XML DTDs and schema are two ways to define an XML-based language—they define the rules to which the language must adhere The rules define the tags that are permissable in that language, what attributes can be used with these tags, and the relationship between the tags One such language definition is Extensible Hypertext Markup Language (XHTML), which is an XML-based version of HTML So, considering the previous example one more time, the XHTML version looks like Listing 4.3 Listing 4.3 Sample XHTML Title goes here First Cell Second Cell If you are familiar with HTML, the majority of the markup in Listing 4.3 should be readily understood As you can see, XHTML is strict: All of your tags must be lowercase and correctly Understanding XSP Tag Markup 49 terminated—attribute values must also be quoted The tag is the root of this XML document and the rest of the document forms a tree, which starts at this root tag The root tag contains the head and body tags, the relationship is described in terms of parents and children So, the tag has two children—the and tags—and the parent of the tag is the tag What’s more, there’s no cheating in XHTML; a page that doesn’t obey the rules is not processed The DOCTYPE declaration at the beginning of the markup declares what the markup contains and is used by whatever browser processes the markup to make sure that the rules are obeyed The DOCTYPE is not mandatory and is not declared within XPages markup, but it is emitted in the generated HTML response So, it is useful to understand this declaration because you have ways to change the default DOCTYPE that XPages uses One other thing might be new to you in this sample, and that is the xmlns attribute The xmlns attribute is a reserved XML attribute and is used to define an XML namespace An XML namespace qualifies the tags and attributes in an XML document, meaning that it declares that these specific tags belong to a specific XML language So, the xmlns attribute in the previous example specifies that all the associated tags belong to the declared XHTML namespace The usefulness of XML namespaces is not immediately obvious; however, consider the following problem: What if you want to create an XML document that contains tags from two different XML languages? Different languages have different tags, and the XML author needs to be able to specify which language specific tags belong to Different languages might use the same tag name, so it is critical to differentiate one from another This is where XML namespaces are your friend; in the previous example we used an abbreviated form of the xmlns attribute The following form, which includes a namespace prefix, can also be used: xmlns:xhtml=”http://www.w3.org/1999/xhtml” This form of the xmlns attribute allows you to specify a prefix, and all tags that use this prefix belong to the associated namespace An XML document that contains multiple namespaces is referred to as a compound document Listing 4.4 shows an XML document that contains multiple namespaces Listing 4.4 XML Document with XHTML and XForms How continues 50 Chapter Listing 4.4 Anatomy of an XPage (Continued) Bloggs First name: Last name: This example starts with an XML processing instruction: This defines the version and encoding of the XML document All XPages contain this same instruction and are encoded as UTF-8, which means unicode is used by default Chapter 10, “Custom Controls,” shows you how useful XML namespaces can be This ends a brief tour of XML More XML tips are provided throughout this chapter, but for now, let’s look at the XPages application of XML XPages XML Syntax By now, you know that XML can be used to define new applications In XPages, XML is used to define a declarative programming model—a way to program where you define what you want done but not how to it You already saw how a basic application can be created using XPages without the need to write a single line of code You won’t always be able to that, but you’ll be pleasantly surprised by how much you can acheive without writing code So, the XPages markup allows you to Create the user interface for your application Define the data that will be manipulated and displayed Define the business logic to be executed in response to events that occur Therefore, you need tags that represent the building blocks for an application Each tag in XSP markup corresponds to a user interface control, a data source, predefined business logic, or a Understanding XSP Tag Markup 51 property used by one of these components There is a well-defined interaction between the user interface, data, and business logic components You must learn how the various components intereact to program using XSP Each component can be configured to provide a variety of behaviors In XSP, you program by creating a hierarchy of tags and and setting the attributes of these different tags This process allows you to describe a user interface, its data, and what happens when the user interacts with this user interface So, you are telling XSP what to in your application rather than how to it This is the power of declarative programming; applications repeat a lot of the same behaviors and all this logic is implemented, tested, and debugged just once for each and reused many times If that was all XPages supported, people would quickly run into limits; however, because of its extensible architecture, you can also add your own custom business logic and create your own components to extend the programming model Let’s start by creating a new XPage and then switching to the Source view, as shown in Figure 4.1 Source View Figure 4.1 New XPage Each new XPage is an XML document, and every XML document must have a root tag The root tag for every XPage is the tag (not to be confused with a Notes view) Why view? Here, you begin to see the XPages heritage emerging, the root of a JavaServer Faces (JSF) component hierarchy is the tag, and this convention has been adopted in XPages (The relationship between XPages and JSF is discussed in Chapter 5.) XPages markup allows you to create a view that is displayed as HTML and the tag represents the component that is root of this HTML document—effectively, this notion of a view maps directly to the HTML tag The XPages namespace is www.ibm.com/xsp/core (no, there is nothing at this URL) and the default prefix is xp This namespace is reserved for use by IBM, because all namespaces beginning with www.ibm.com are When you need to define your own namespace, the convention is to use a URL that starts with your company’s web address to ensure that there are no collisions 52 Chapter Anatomy of an XPage Simple Properties The first thing you will learn is how to alter the behavior of the tag by changing its properties XML allows you to set attributes on a tag, and this is one way you can set the properties of the component associated with that tag To get a list of all the properties associated with a particular tag, perform the following steps: Expand the XPage outline and select the tag (in this case, the tag labelled XPage) Select the All Properties tab from the Properties page All the properties for that tag are listed, and they are categorized based on function: • Acessibility: Properties used to make your application more readily interpreted by assistive technologies • Basics: General category of properties • Dojo: Properties that are used by Dojo (this use of Dojo in XPages is covered in Chapter 11, “Advanced Scripting”) • Data: Optional properties that allow data to be associated with the tag and its children • Events: Properties that are events to which the component can respond • Styling: Properties that control the visual appearance of the component To set the value of a property, you can select the cell in the Value column and directly type in the value For example, to set the background color of the XPage to a shade of light gray, edit the style property The style property allows you to use Cascading Style Sheets (CSS) syntax to change the appearance of the XPage Select the style property and type in the following value: background-color:rgb(0,0,255) When you this, the markup changes as you type, and you see the style attribute being added to the view tag, as shown in Figure 4.2 When you select a cell in the value column of the All Properties tab, you might see a button to the right of the editable value area This button allows you to launch an external property editor if one exists for the property you are currently editing An external property editor provides a GUI that simplifies the editing of a specific property type for well-known property types (You learn how to work with property editors in Chapter 10.) So, if you are not a CSS expert, you can open the property editor and have a user-friendly interface that allows you to set the style property, as shown in Figure 4.3 If you switch back to the Design tab for this XPage, you see that the page now has a blue background Understanding XSP Tag Markup XPage Tag AllProperties Tab Figure 4.2 Editing a tag property Figure 4.3 Style Editor 53 Edit Style Property 54 Chapter Anatomy of an XPage Complex Properties XML attributes can be used to set properties that have primitive data types (such as strings, integers, and so on); however, not all the properties of a component are primitive types Nonprimitive properties are referred to as complex properties Complex properties are represented as their own tags in the XPages XML vocabulary Listing 4.5 shows an example of how to set the data property Listing 4.5 Setting the Data Property A tag that begins with the prefix xp:this is interpreted in a special way in XPages This tag indicates that a property is being set on the parent tag, and the name of the property is the part of the tag name that follows the this prefix These tags are referred to as this tags and the syntax is referred to as the xp:this (or just this) syntax The value of the property is the child of the this tag In the previous example, the data property of the view component is being set to a Domino document (as represented by the xp:dominoDocument tag) Data source tags are discussed in detail later in the section, “Data Sources.” To summarize, the xp:this syntax allows you to set complex properties on the parent tag Complex Values The this tag syntax is generic and can be used to set any property of an XPages component Listing 4.6 demonstrates how you set the id property using xp:this.id This is for educational purposes only; it’s not recommend for use in practice Listing 4.6 Setting the ID Property Using the xp:this Syntax view1 This time, instead of using an XML attribute to set the property value, the this syntax and the value of the property is the text nested between the start and end tags As previously mentioned, you can set string property values using the XML attribute syntax; however, XML imposes numerous limitations on attributes—they cannot contain certain characters (, ”) and linebreaks Most of the time, this is not a problem, but there is one main case where this is a major Understanding XSP Tag Markup 55 issue When using the event properties, you typically want to add some JavaScript code that will execute when that event is triggered Your JavaScript code might span multiple lines and might need to include some characters that are illegal for an XML attribute XML has a solution to this problem: character data (CDATA) section A CDATA section allows you to add content to an XML document that an XML parser interprets as character data and not markup A CDATA section starts with the following sequence of characters: and ends with this sequence: ]]> TIP The delimiters used in a CDATA section are intentionally meant to be obscure— something that would not normally appear in an XML document and, as such, are easily forgotten By default, when you use the XPages Editor to add JavaScript, it is included in a CDATA section So, if you forget the exact syntax of a CDATA section, using the Script Editor is a quick way to generate one Listing 4.7 shows how to add some JavaScript that executes on the server after the XPage loads This example uses the XPage afterPageLoad event property; this event is triggered after the XPage first loads and the associated business logic is executed Listing 4.7 Using a CDATA Section with the xp:this Syntax TIP When you preview this page in the Notes client, you can see the message that was printed using this JavaScript by viewing the trace (Help > Support > View Trace) This trace file contains all server logging and server print statements Computed Properties So far, you have seen how to set static property values (values that are fixed to a specific value that is known at the time the XPage is created) But, what happens if you need to compute the value of a property dynamically? For example, the value is not known when the page is created, 56 Chapter Anatomy of an XPage but it needs to be computed based on some data that will be available at the time the XPage executes, such as the current username or current time A good example of this is deciding when to display some part of the user interface XPages uses the rendered property to control when part of the user interface is displayed This is a boolean property, so the valid values are either true or false (in the UI, this property is called Visible) If you go to the All Properties tab and edit this property, you are presented with a drop-down that lists the valid values, but also notice a small blue diamond By default, this diamond is empty, which means that the property value is not being computed If you add business logic to compute the property value, the diamond changes to a solid blue diamond This convention is used throughout the user interface to allow you to easily determine where business logic is being used Select this diamond and you are presented with an option to compute the property value, as shown in Figure 4.4 Figure 4.4 Computing a property value The Script Editor is opened to allow you to add your own JavaScript business logic to compute the property value, as shown in Figure 4.5 Figure 4.5 Script Editor Understanding XSP Tag Markup 57 The Script Editor is discussed later in this book, but for now, let’s look at how computed values are presented in the XPages markup Listing 4.8 uses a Computed Field control that displays the computed value and a submit button, which is labeled “Refresh”, to cause the page to be redrawn Listing 4.8 Computing a Value Dynamically TIP Controls that can display HTML or XML (such as a Computed Field or rich text editor) support a property called escape This property indicates that the contents need to be encoded before being displayed so that characters senstive in HTML or XML (such as ) are escaped and display correctly A dynamically computed expression starts with the #{ character sequence, followed by the programming language (for example, javascript), then a : character, then the computed expression, and it ends with the } character Here is the generic syntax of a dynamically computed expression: propertyName=”#{:}” Preview the page in the Notes client and the number of seconds is displayed, as shown in Figure 4.6 Computer seconds Figure 4.6 Preview a computed value 58 Chapter Anatomy of an XPage Select the submit button, the page refreshes, and the number of seconds is updated This is because the value is being computed every time it is accessed It is important to know that the property is computed each time it is accessed, which might be more often than you may expect The property might be accessed multiple times as a page is being processed, so be careful if you’re performing expensive computations Another option is to compute the property value once, when the page is loaded Listing 4.9 shows a modified version of the previous example, where the value is computed just once when the page loads Listing 4.9 Computing a Value when the Page Loads Computed expressions are evaluated either every time they are accessed, dynamically or just once when the XPage loads The only difference between a dynamically computed expression and one that is computed when the page loads is the start delimiter The start delimiter for a computed expression that is only evaluated when the page loads is the ${ character sequence Here is the generic syntax of a computed expression that is evaluated when the page is loaded: propertyName=”${:}” With that one small change, submitting the page no longer changes the computed value, because it does not get reevaluated after the initial page load Listing 4.10 shows example XPages markup for a more complete sample that shows dynamically computed and computed-on-page-load values side by side When you preview this sample, initially both values should be the same (or at least within second of each other), but each time you click the submit button, only the dynamically computed value changes Listing 4.10 Complete Computed Values Sample Understanding XSP Tag Markup 59 Compute dynamically: Compute on page load: Data Binding The computed values you saw in the previous section are read only But, what if you want to bind a control to a value and allow the control to read and update that value? You already saw an example of this in Chapter 3, “Building Your First XPages Application,” where an edit box was used to edit the value in a Notes document Listing 4.11 shows the basic syntax of how to bind an edit box to a field in a Domino document so that the edit box can be used to read and write the field value 60 Chapter Listing 4.11 Anatomy of an XPage Data Binding to a Notes Document Field Notice that, again, the #{ and } delimiters have been used around the value to which the control is bound In this case, no programming language is specified When no language is specified, the default Expression Language (EL) is used EL is a scripting language that provides access to Java objects, and it is discussed in Chapter Here again, you see XPages’ JSF heritage emerging, because EL is what JSF uses by default for data binding EL allows you to bind the edit box value to a property of some object (in this case, a field named TextField in a Domino document) This data binding is bidirectional (it can be used to read and write the property value) EL is discussed in more detail in Chapters and XPages Tags Now that we’ve covered the basics of the XPages syntax, let’s look at the different types of tags that XPages supports There are nine categories of tags: • Data sources • Controls • Containers • View resources • Converters • Validators • Simple actions • Client-side scripting • HTML All the tags are listed by category, and we look closely at what the tags in each category are used for and the specialized behavior of each type of tag Data Sources 61 Data Sources The data source tags represent the data that users of your application can read and possibly create, update, and delete A data source can be set as the property of the main xp:view tag, and this makes the data available to the entire XPage Domino applications are inherently a special type of database that allows you to store application data as Domino documents A Domino document stores the data as a collection of fields, each with its own data type The structure of the data in a Domino document can be specified by creating a form, which acts as a schema for the fields, when a document is created using that form A Domino document also contains special reserved fields that contain information about the document (metadata), such as when the document was last modified Domino documents are discussed in Chapter 7, “Working with Domino Documents.” The data from a collection of Domino documents can be read using a Domino view When a Domino view is created, you must specify the types of documents it will contain (such as documents created with a particular form) and what data from those documents is displayed in the view (specific fields or event values computed from multiple fields) Domino views are discussed in Chapter 8, “Working with Domino Views.” Not surprisingly, data source tags correspond to Domino documents and Domino views, as described in the following sections Domino Document An xp:dominoDocument tag can be added to an XPage when you want to use that page to create a new document, edit an existing document, read an existing document, or any combination of these actions Always specify the var and formName properties The var property defines a variable name by which the Domino document can be referenced by other tags in the XPage For example, when binding a control to a Domino document, the value of the var property is the first part of the value binding expression (normally set to document1) The formName property defines the form associated with the Domino document As previously mentioned, the form defines the structure of a document created with that form, and the XPages editor uses the information when creating binding controls to the Domino document By default, the Domino document being operated on is contained in the same Domino database as the XPage; however, you can specify another database on the same or even another server by using the databaseName property Listing 4.12 demonstrates how to edit the first Domino document in the Countries view Listing 4.12 Domino Document Sample continues 62 Chapter Listing 4.12 Anatomy of an XPage (Continued) Country name: Country code: Domino View A xp:dominoView tag can provide access to the collection of documents associated with a Domino view Listing 4.13 shows how a Domino view data source, which is configured on the top-level xp:view tag, can be accessed by a data table control and a Computed Field The data table control iterates over the data to which it is bound (in this case, each entry or row in the view) The data table makes the row data available by using the variable name specified by the var property (for example, country) The row data can then be accessed, and values from the current row are displayed by a Computed Field The example shows how to access the column value using JavaScript and EL The data table control is discussed in more detail in the section, “Containers.” The Domino view data source is most often used with the view control, and Chapter gives a detailed explanation Listing 4.13 Domino View Sample Data Sources 63 Data Context The xp:dataContext tag provides access to data values within an XPage Strictly speaking, this tag is not a data source because there is no underlying data store; however, it is used in a similar way A data context can be used compute a value (If you needed to compute a value based on some fields in a Domino document, you could compute the value once using a data context and then make the result available through a variable that can be referenced throughout the XPage.) Listing 4.14 demonstrates how a data context is configured to compute a date value and then how the value is referenced by a Computed Field Listing 4.14 Data Context Sample 64 Chapter Anatomy of an XPage Controls The control tags represent the user interface widgets that you can use to create your application interface There are five broad categories of controls: • Controls that support both the display and modification of a data value • Controls that provide a way for a user to trigger some action in the application (these include buttons and hyperlinks) • Controls that allow the user to select one or more predefined values • Controls that are used to display purposes only (for example, the user cannot interact with these controls to directly modify the data) • Controls that are used to upload and download files Each group of controls shares common properties, and the behavior of those properties is basically the same across the group If you can understand how a property applies to one control, you can apply that knowledge to other controls of the same type Control properties belong to the following categories: • Styling: Controls the appearance and some behavior of the control All styling in XPages is performed using CSS, which is an industry standard • Events: Provide a way to add logic that will be executed when an event associated with a control is triggered All controls support a set client-side JavaScript event, which can be scripted • Data: Most, but not all, controls can be bound to data, either to display/modify the data or manage the data for their child controls • Dojo: Adds Dojo functionality to a control • Basics: All controls have some shared basic properties (such as control ID, flag indicating if the control should be rendered, and so on) • Accessibility: Provides more information about a control for use by assistive technologies This section helps you to learn how to read the markup for the XPages control and understand what that control does Most controls are represented by a single tag in the markup, which makes understanding them straightforward Some controls are represented by a collection of tags (such as a data table control) Other controls are normally used together in standard patterns This section takes you through some of the most common patterns for the different types of controls Editing Controls Editing controls are used to edit data values in your application Each control can be bound to a data value and used to display and modify that value This section reviews the following controls: Controls 65 • Edit box • Multiline edit box • Rich text • Date time picker Here are some other things that you can with editing controls: • One or more validators can be applied, which checks that the value entered by the user adheres to certain constraints • A single converter can be applied, which converts the user-entered string into another data type (such as an integer value) • Business logic can be written, which executes when the value bound to the control changes • Type ahead can be enabled for an edit box, which provides a list of suggestions as the user types a value Converters and validators are covered later in this chapter in the sections, “Converters” and “Validators,” respectively Edit Box The edit box xp:inputText tag adds a text edit control to the page Listing 4.15 demonstrates the most common use case where the edit box is bound to text field in a Notes document Listing 4.15 Edit Box Bound to a Notes Document Field To enable type ahead, add the xp:typeAhead tag as a child of the edit box The type ahead is responsible for adding new behavior to the edit box, which displays the appropriate list of suggestions as the user types Listing 4.16 demonstrates a fixed list of suggestions that is provided using a comma-separated list, but you can also dynamically compute the list of suggestions (for example, using a column from a Notes view) Preview the associated sample and type the letter A in the text field to see the type ahead in action 66 Chapter Listing 4.16 Anatomy of an XPage Adding Type Ahead to an Edit Box Multiline Edit Box Listing 4.17 shows the markup for a multiline edit box that has been configured to display a specific size The size is based on the number of rows and columns of text to display and, therefore, resizes itself if the default font changes Type ahead is not supported for multiline edit boxes Listing 4.17 Multiline Edit Box Bound to a Notes Document Field Controls 67 Rich Text A rich text edit xp:inputRichText tag allows the user to enter text with some basic rich formatting using HTML syntax Listing 4.18 shows a rich text control being used to edit a rich text Notes field The sample also has a Computed Field that displays the contents of the Notes field, and a submit button so you can add rich text, submit, and then see what the rich text looks like The rich text content is stored in MIME format and is rendered to HTML for display The Computed Field is configured to escape the rich text, which will display the rich text markup You can experiment with changing this escape property to false, and you will see that the Computed Field now displays the rich text instead of the markup Listing 4.18 Rich Text Control Bound to a Notes Document Field Figure 4.7 shows this sample previewed in the Notes client You see that the rich text markup is displayed in the Computed Field 68 Chapter Anatomy of an XPage Rich text markup Figure 4.7 Rich text sample Date Time Picker The date/time picker xp:dataTimeHelper tag is a helper that adds some behavior to an edit box that helps the end user enter date and time values in the correct format Components that add behavior to another control are typically nested as children of the control they are enhancing This is the case for the date/time picker Listing 4.19 demonstrates the default date/time picker settings Listing 4.19 Date/Time Picker Sample A date/time picker is constructed from an edit box with two children: a date/time converter xp:convertDateTime and the date/time helper xp:dataTimeHelper The data being entered is stored in a date format, and the converter is required to handle data conversion The date/time helper displays a button beside the edit box that can be used to open a date or time or date and time picker user interface Listing 4.20 shows how to use the date/time picker to enter the date only, time only, and date plus time Controls 69 Listing 4.20 Date Only, Time Only, and Date Plus Time Sample                        Listing 4.20 uses  , which is the entity number for a nonbreaking space and is used to add space between the date time picker controls When you preview this example, you see buttons beside each edit box and, when you click a button, the appropriate picker control is displayed to allow you to enter either a date, time, or both, as shown in Figure 4.8 70 Chapter Date picker Figure 4.8 Time picker Anatomy of an XPage Date\time picker Date picker, time picker, and date/time picker Command Controls Command controls provide one way for the user to trigger some business logic within your application The following controls can trigger the execution of server-side business logic in response to a user action: • Event handler • Button • Link Event Handler Chapter presented some examples where buttons were used to save a document or cancel the editing of a document In those examples, an xp:eventHandler tag was automatically added as a child of the button to submit the page and optionally save the document The event handler is not displayed on the rendered page Instead, it is added as the child to another control, which is visible on the page, and then it listens for client-side JavaScript events coming from its parent and will submit the page Listing 4.21 shows how an xp:eventHandler tag can be added to a Computed Field control to force a page submit when the Computed Field is clicked Listing 4.21 Using an Event Handler to Submit an XPage when a Computed Field Is Clicked The event handler is normally used in conjunction with a button; however, as you can see from the previous example, it can be used with any control The event handler has built-in functionality that allows you to automatically save the documents associated with the XPage Setting its save property to true automatically saves document updates The event handler is also used when you want to cancel editing and move to another page In this case, the immediate property needs to be set to true; this causes all processing of the submitted data to be ignored The event handler is covered in Chapter 6, “Building XPages Business Logic.” Button The xp:button tag is normally used in conjunction with an event handler It is a command control, and it can directly invoke server-side JavaScript business logic Listing 4.22 demonstrates using a button click to execute some server-side JavaScript that manipulates the rendered property of an image control The server-side JavaScript code gets the component associated with the image control and toggles the rendered flag and then, when the page is redisplayed, the image is either shown or hidden When you run this sample, you see that, initially, the image is displayed and the label of the button is Hide Image Clicking the button submits the page and, when it is redisplayed, the label of the button is Show Image, and the image will no longer be displayed Listing 4.22 Executing Server-Side JavaScript Business Logic in Response to a Button Click continues 72 Chapter Listing 4.22 Anatomy of an XPage (Continued) Link The xp:link tag displays a hyperlink on the rendered page The link control is normally used to navigate to another XPage, open a URL, or jump to another part of the current page (specified by an anchor) A link can also be used in conjunction with an event handler to submit the XPage and execute server-side JavaScript business logic Listing 4.23 demonstrates the most common usages of the link control The value property of the link control can be set to either a location of an XPage within the current application or any URL link From Designer, you can specify the link type as being either one of the following: • Open Page allows you to specify the page to open • URL allows you to open HTTP URL or an anchor, which allows you to navigate to another part of the current page Listing 4.23 Opening Another XPage, Web Page, and Submitting the Current Page with a Link Controls 73 TIP Often, you might want to navigate to a different XPage after performing some business logic The next XPage may differ, depending on the outcome of the business logic You can use the xp:navigationRule tag to associate an XPage with an outcome The business logic can return an outcome value and change which page is displayed next Listing 4.24 contains the source code for two XPages that use navigation rules to navigate from one to the other The action associated with the button is coded to the outcome in the navigation rule, and this is sufficient to trigger the navigation to the specified page Listing 4.24 Navigation Rule Sample Navigate A _ Navigate B 74 Chapter Anatomy of an XPage Selection Controls Selection controls allow the user to enter data by selecting one or more values from an available list of options So, the data that can be entered is constrained by the options that you present to the user In this section, you see how to specify what options are available to the user for each control Each example shows the control bound to a field in a Notes document, a Computed Field, and a submit button When you run the example, you can submit the page and see how changing the selection in the control impacts the values that is saved to the document This section reviews the following controls: • Listbox • Combo box • Checkbox • Radio button • Checkbox group • Radio button group The xp:listBox tag presents a list of options to the user, and the user can select either a single value or multiple values, depending on how the listbox is configured Listbox The listbox example in Listing 4.25 shows a single selection listbox and contains a fixed list of values that are coded into the XPage using xp:selectItem tags (which represent the listbox items) Each item has a label, which is what is displayed to the user, and a value, which is what is saved to the document When you preview this sample, select a language, and submit the page, you see that the current value is set to the item value instead of the item label Listing 4.25 Listbox Sample Controls 75 Current value: The listbox example shown in Listing 4.26 shows a multiple selection listbox and how the options are computed using server-side JavaScript The server-side JavaScript expression returns an array of strings, where each string is a label/value pair delimited by the | (pipe) character These strings are then automatcially converted into a collection of select items by the XPages runtime Note that the computed expression is computed only once, when the page is loaded as indicated by the initial $ in the computed expression This makes sense, because the list of options shouldn’t change every time the page is submitted When you preview this sample, notice that you can select multiple items from the listbox When you submit the page, you see that the current value is set to a comma-delimited string that contains the item values of the selected items Listing 4.26 Computed Listbox Sample Computed List continues 76 Chapter Listing 4.26 Anatomy of an XPage (Continued) Current value: Combo Box The xp:comboBox tag is a visually more compact form of a single-selection listbox control It presents a list of options to the user, and the user can select a single item Listing 4.27 demonstrates a combo box with a fixed list of options Listing 4.27 Combo Box Sample Controls 77 Current value: Figure 4.9 shows a Notes view that is used to populate the values in the combo box sample shown in Listing 4.28 The third column of the Notes view contains the options to be displayed The lookup column contains the values needed for each select item that will be added to the combo box Each value in the third column contains the label and value for the select item that will be created Instead of using tags, the value property of the xp:comboBox tag has a JavaScript expression that reads the third column of the Countries view When this JavaScript expression is evaluated, the combo box selections are automatically added This JavaScript expression uses a server-side JavaScript @function to access the database column (using @DbColumn(), in fact) and the current database (@DbName()) Server-side JavaScript @ functions are covered in Chapter You can see from Listing 4.28 that it is easy to populate a combo box from the contents of a view Readers familiar with Notes programming know that this means that, as your application supports more countries, the combo box automatically displays the new options after the corresponding Notes document is added to the Countries view 78 Chapter Anatomy of an XPage Date picker Figure 4.9 Listing 4.28 Countries view Computed Combo Box Sample Current value: Controls 79 Checkbox A xp:checkBox tag allows the user to select or unselect a particular option Depending on the option the user selects, the checkbox returns a different value The default values for a checkbox are true and false The checked and unchecked values can be set to any arbitrary value that is appropriate for your application In Listing 4.29, the check and unchecked values are set to CHECKED and UNCHECKED, respectively Listing 4.29 Checkbox Sample Current value: 80 Chapter Anatomy of an XPage Radio Button A xp:radio tag allows the user to select only one option from a list of selections (the options are all mutually exclusive) Radio buttons are always created in a group, because it doesn’t make sense to have a single radio button on an XPage When one radio button in a group is selected, all the other radio buttons are automatically unselected You can also specify which radio button is selected by default Listing 4.30 provides three options (Red, Green, and Blue, with Red being selected by default) The label displayed to the user differs from the value saved when the user selects that radio button For example, the first radio button will have a label of Red (as denoted by the text property), but the saved value will be RED (as denoted by the selectedValue property) Listing 4.30 Radio Button Sample Current value: Controls 81 Checkbox Group A xp:checkBoxGroup tag allows the user to select or unselect from a list of options Depending on the options the user selects, the checkbox group returns a different value The value is a comma-delimited string made up of the item values for all the selected items In Listing 4.31, the item values are 1,2,3 and, when all three items are selected, the value stored on the document will be 1,2,3 Listing 4.31 Checkbox Group Sample Current value: Radio Button Group A xp:radioGroup tag allows the user to select only one option from a list of items (the options are all mutually exclusive) You use a radio button group in preference to individual groups when 82 Chapter Anatomy of an XPage all the items are at the same level in the hierarchy and are being grouped together without any other controls or text between them Listing 4.32 shows an example of this, which is functionally equivalent to the earlier example that used individual radio buttons Listing 4.32 Radio Button Group Sample Current value: Display Controls Display controls present data to the user These controls not support any editing features The following controls are reviewed in this section: • Label • Computed Field • Image Controls 83 Label The label xp:label tag provides a way for you to specify information about another control, typically the data to be entered for an input control (such as an edit box) Labels can be specified by entering text next to the input control; however, doing this causes a problem for screen readers For example, when a visually impaired user sets focus on an edit box, his screen reader looks for the label associated with that control and reads out the label text If you not associate a label control with its corresponding input field control, a screen reader will not have the critical hint and your application is not fully accessible Listing 4.33 demonstrates how to associate a label control with an edit box Listing 4.33 Label Sample Computed Field An xp:text tag presents the value of some computed expression to the user The value can be computed dynamically each time the page is displayed or alternatively when the page is first loaded Listing 4.34 demonstrates two Computed Fields, both of which have the same computed value: Bold The first Computed Field presents the computed value as typed in the previous sentence The second Computed Field presents the computed value in Bold format This is because the second Computed Field has its escape property set to false so that the computed value is not encoded for presentation as HTML Listing 4.34 Computed Field Sample Bold’}]]> continues 84 Chapter Listing 4.34 Anatomy of an XPage (Continued) Bold’}]]> Image The xp:image tag allows you to add graphics to an Xpage, as shown in Listing 4.35 Images can be imported and stored as part of your Domino application as image resource design elements When you add an image control to an XPage, you can select from the images that have been imported into your application You can find the images under Resources > Images in the application navigator Listing 4.35 Image Sample File-Handling Controls The file-handling controls allow you to upload and download files from the Domino document data store The files are saved as attachments to the current Domino document The following controls are reviewed in this section: • File Upload • Filed Download File Upload Listing 4.36 demonstrates how to use the File Upload control to attach a file to a Domino document The xp:fileUpload tag is bound to a rich text field in the Domino document and, when the Domino document is saved, the file specified by the user is attached to the field in the document Listing 4.36 File Upload Sample Controls 85 86 Chapter Anatomy of an XPage File Download Listing 4.37 shows how to use the File Download control to download an image attached to the first document from the PeoplePhotos view The xp:fileDownload tag is bound to the rich text field in the Domino document and displays all files that are attached to this field The File Download control presents a list of the files that can be downloaded by the user and are retrievable by clicking the associated link within this control Listing 4.37 File Download Sample Containers Containers are a specialized group of controls that can contain other controls Some containers are used for layout purposes, but some can be used to provide additional behavior to the controls they contain Several containers are designed for use with collections of data (such as the view, data table, and repeat controls) Other containers allow you to more efficiently use the real estate within your XPage (the tabbed panel and section controls) The following containers are available for use within XPages: • Panel • Table • View • Data table • Repeat • Include page • Tabbed panel • Section The following sections describe these containers in detail Panel The panel container is used to layout its children within a rectangular area of an XPage A panel allows you to manipulate its children as a group In Listing 4.38, the background-color for the panel is set, and this changes the background for the Computed Fields contained within the panel You could also show or hide a group of controls by changing the rendered property of their parent panel Another powerful feature is the ability to scope data using panels In Listing 4.38, there are two document data sources—one associated with the XPage and one associated with a Panel within the XPage Both document sources use the same variable name: document Three Computed Fields reference the document variable and, at first glance, you might expect that they will reference the same data source When you run this example, you see that the first and third Computed Field reference the document data source associated with the XPage The second 88 Chapter Anatomy of an XPage Computed Field, however, references the data source associated with the panel So, the document data source is different for controls within the panel as opposed to those outside the panel, because the data source associated with the panel is scoped to the children of the panel and is not made available to controls outside the panel Listing 4.38 Panel Sample Another useful feature of the panel container is the ability to assign access control to a panel This allows you to the following: • Prevent certain users or groups of users from accessing part of an XPage • Provide read-only access to part of an XPage for certain users or groups of users Listing 4.39 includes four panels, each with an associated access control list (ACL) An ACL ( tag) determines what access a user or group has to the associated content (the contents of the panel) An ACL contains a list of entries ( tag), and each entry has a type, access rights, and optionally the name of the user or group In Listing 4.39, the access is set as follows: Containers 89 • The first panel defaults to no access, so when you run the sample, you cannot see the contents • The second panel provides reader access, so you can only read the contents; editing is disabled • The third panel provides editor access, so you can edit the value • The fourth panel appears to provide multiple conflicting access but, in fact, the user gets the highest access available This is because a user might be in a user group (who might have read-only access) and an administrators group (who might have editor access) and, in this case, the user gets higher access rights Listing 4.39 Access Control List Sample continues 90 Chapter Listing 4.39 Anatomy of an XPage (Continued) TIP The tag can be used with the XPage view ACLs are covered in detail in Chapter 17, “Security.” Table A table container provides a way to lay out controls in an HTML table The table is made up of one or more rows with each row containing one or more cells Cells can span multiple rows or multiple columns The style can be set for an individual cell or the entire row The vertical and horizontal alignment for rows and cells can also be set Listing 4.40 includes a table with some cells spanning multiple columns and rows You can see that the syntax is similar to that used for a regular HTML table The reason XPages provides its own table tags is so that the associated components can be manipulated in JavaScript like all the other XPages controls Containers Listing 4.40 91 Table Sample 1 2 3 4&8 5&6 7 View The view control provides a way to display collections of Domino documents An entire chapter is dedicated to the view control, so for now, the basic functionality is introduced Listing 4.41 shows the default markup that is generated when you drag a view onto an XPage and configure it to display data from an existing Notes view The default view control has the following features: • A pager is displayed at the top of the view control to allow users to page over all the documents in the view Only the contents of the view control are retrieved and modified during paging • A view column is created for each column of data Each column has a header that displays the column title The view column displays the contents of the Domino view column with the same name • The associated view data source is defined within the view control and scoped to that control Listing 4.41 View Sample Facets In Listing 4.41, notice that the view has a property called facets (the value being set is a complex property so the this.facets syntax is used) Also notice that the page tag has an attribute called xp:key These two constructs work together to provide a mechanism that allows child controls to be placed in a specific place within their container When you preview the view sample, you see that the pager is displayed at the top of the view This is because the view has a reserved area at the top, and the pager is configured to be placed within that region This reserved area within a container is called a facet Each facet has a name To place a control within a facet, you must add that control to the facet’s property and use the xp:key attribute to specify the name of the facet Facets are stored using a map with the facet name being the key The special xp:key attribute is used by the XPages page loader to assign a complex property to a map The order that the controls appear in the facets property is irrelevant; only the value of the xp:key attribute is important Listing 4.42 shows a view with two pagers: the first is placed in the footer of the view and the second in the header area Each control has defined facet key values that correspond to specific areas where a facet can be displayed Containers Listing 4.42 93 View with Two Pagers TIP In Chapter 10, you learn how to extend XPages by creating your own custom controls When you create a custom control, you need a way to specify the location of its facets The xp:callback tag provides a way for custom controls to specify the location of a facet 94 Chapter Anatomy of an XPage Data Table The data table provides the same functionality as the view control, but without the adaptations to make it work seamlessly with a Domino view data source In fact, the view control extends the data table control and adds these adaptations It is possible to create the same behavior using a data table, and this is a good way to demonstrate what data tables can and to improve your understanding of what a view control does under the covers Listing 4.43 shows a data table configured with the same functionality as a standard view The contents of the data table are defined using xp:column tags Each column can contain an arbitrary control, including other containers A column header can be specified using the header facet The data table is bound to a collection data value (in this case, a Domino view) It iterates over a dataset and renders the contents of each column once for each entry The value of the entry (such as the row data) is made available to the children in the columns using the name specified in the var property The children in the column can extract values from the row data by using computed expressions In Listing 4.43, you see that the Computed Fields are configured to display the value of a specific column in the corresponding row of the Domino view The data table provides much more flexibility than the view control, but as you can see, it requires more work to configure Listing 4.43 Data Table Sample Repeat The repeat control is the last in the family of containers that provide a way to iterate a dataset The repeat is useful when building modern style user interfaces Unlike the view and data table, the repeat does not limit you to displaying multiple columns of data and controls The first repeat example shows how to display multiple values using a Computed Field and have the values display in a row In Listing 4.44, you can see that the repeat does not impose any layout restrictions on its children Listing 4.44 Repeat Sample The repeat control can also be used to create controls Consider the data table example in Listing 4.43 again What if you don’t know how many columns are needed in the data table when you are designing the XPage (for example, if the dataset varies depending on who the user is)? The repeat control can be used to create the correct number of columns and then it can remove itself from the XPage after its job is done Listing 4.45 shows how to this and introduces a new way to work with computed expressions Setting the repeatControls property to true instructs the repeat control to create a new copy of its children for each iteration over the dataset The removeRepeat property tells the repeat control to remove itself after the XPage is built It is important to remove the repeat in this example because, for the data table to work correctly, its children must be xp:column tags So, after the repeat creates the correct number of columns, it needs to be removed to allow the data table to its job The data table is bound to a two-dimensional array with three columns of data and ten rows of data The repeat is bound to an array, the size of which defines the number of columns that will be created (such as three columns), and the contents of this array are used as the titles of the columns (for example, A, B, C) The Computed Field in the header facet of each column is bound using a load time computed expression; this means that the title is computed once and remains static thereafter The Computed Field, which displays the column value, needs to be a computed value bound to the row data that the data table makes available A load time computed expression is used to compute the dynamic computed expression, which binds the Computed Field to the row data Here’s the sequence of computations for the Computed Field, which displays the data for each column: During page load, the following expression is computed: ’#{data[‘+rowIndex+’]}’ This results in a dynamic computed expression; for example, the first column is #{data[0]} This expression extracts the appropriate value for the two-dimensional array Containers Listing 4.45 97 Repeat Data Table Columns Sample When you preview the example shown in Listing 4.45, you see a table that contains the three columns and ten rows of data with the headings A, B, C, as shown in Figure 4.10 The final repeat example also shows how to create controls using a repeat; this time, radio buttons are created Radio buttons allow the user to select one from a list of mutually exclusive options Defining a group for the radio buttons ensures that only one button can be selected When all the radio buttons are at the same level in the control hierarchy, this works fine; however, when radio buttons are nested inside different containers, this grouping behavior doesn’t work as expected You need to instruct the radio button to skip the correct number of containers for the groups to apply Listing 4.46 demonstrates how the skipContainers property on the radio button is set to to get the group behavior to work correctly By setting the skipContainers 98 Chapter Anatomy of an XPage property to 1, each radio button behaves as if it was a separate control in the containing XPage and, because they appear at the same level in the page hierarchy and they have the same group name, they have a group behavior (only one can be selected at a time) Figure 4.10 Repeat columns sample Listing 4.46 Repeat Radio Buttons Sample Containers 99 Include Page This control allows you to embed the contents of one XPage into another XPage Listing 4.47 includes the view sample and data table sample shown earlier, so you can see the two samples side by side The page name to include can be computed, but only using an expression that is evaluated when the page loads Listing 4.47 Include Page Sample Tabbed Panel This container allows you to organize its children across multiple tabs This allows you to group related controls, which helps the user focus on a particular part of your XPage Listing 4.48 extends the include page sample and adds each included page into a separate tab It also shows how to use a button to navigate between the tabs; this is a common pattern in wizard-style interfaces Listing 4.48 Tabbed Panel Sample continues 100 Chapter Listing 4.48 Anatomy of an XPage (Continued) Section The section container organizes its children in a region that can be toggled between an opened and closed state In Listing 4.49, there are two sections: first, a default section that is closed by default; and second, a section that is surrounded by gray bars on all sides, which is initially open It is also possible to disable the ability to expand and collapse a section, so if, in certain circumstances, it is not appropriate to allow this, that feature can be controlled Listing 4.49 Section Sample XPage Resources 101 XPage Resources For all the example XPages shown in this chapter, all the JavaScript has been included within the page, typically in CDATA sections This procedure is acceptable when the JavaScript code is simple However, as your XPages applications become more complex, the need arises to write JavaScript that might be broken into multiple methods and needs to be shared across multiple, different XPages The same applies for styling; if you apply styles to each individual control in each XPage, it becomes difficult to maintain consistency across all of your XPages For example, if you decide to change the standard look for your buttons, you have to change every XPage that contains a button control These are the two most common examples of the need to associate resources with your XPage To solve these problems, XPages supports the ability to link to external resource files You have already seen an example of this, where the image control allows you to link to an image resource that was created in the application Six types of resources can be associated with an XPage: • Script library • Style sheet • Resource bundle • Dojo module • Generic resource • Metadata The sections that follow examine these resources in greater detail Script Library XPages supports linking to client-side or server-side JavaScript script libraries To create a script library, follow these steps: Choose File > New > Script Library In the New Script Library dialog (shown in Figure 4.11), enter a name (such as ServerJavaScriptSample), and change the type to Server JavaScript Choose OK, and the new script library opens in the JavaScript™ editor (see Figure 4.12) Next, create a simple JavaScript method that will be referenced later from an XPage: Use the keyword function to start a new method (see Figure 4.12) Give the method a name (such as getSomeText) This method does not take any parameters In the body of this new method, return a static string (such as Some Text) 102 Chapter Figure 4.11 New Script Library dialog Figure 4.12 JavaScript editor Anatomy of an XPage Finally, the script library can be referenced in an XPage, and the method you created can be called (see Listing 4.50) The xp:script tag links to a script library This tag can be added as a child to the resources property of the xp:view tag This makes the contents of the script library available within the XPage The script library can be created for either client-side or server-side scripting If the script library is for client-side use, a link to the library will be created in the head section of the HTML page The method that was defined can now be invoked from within the XPage In Listing 4.50, you can see the method being used to set the value property of a Computed Field XPage Resources Listing 4.50 103 Script Library Sample The use of JavaScript libraries, both client-side and server-side, is covered in Chapter 11 Style Sheet Follow these steps to create a style sheet: Choose File > New > Style Sheet Resource In the New Style Sheet dialog (see Figure 4.13), enter a name (such as StyleSheetSample) Choose OK, and the new style sheet opens in the style sheet editor (see Figure 4.14) Figure 4.13 New Style Sheet dialog 104 Chapter Anatomy of an XPage Next, create a button style class that will be referenced later from an XPage: Use the name sample to indicate that this style only applies to all elements with style class set to sample (see Figure 4.14) In the body of this new style class, set the various styles that you want to apply Figure 4.14 Style sheet editor The style sheet can now be referenced from an XPage, and the style class you defined can be applied to controls The xp:styleSheet tag links to a style sheet resource This tag can be added as a child to the resources property of the xp:view tag Listing 4.51 demonstrates how the style class you just defined can be applied to a button Listing 4.51 Style Sheet Sample The use of style sheets is covered in Chapter 14, “XPages Theming.” Resource Bundle This complex property is used to load a resource bundle file and make its contents available within the XPage A resource bundle file is a text file that contains name/value pairs and is the XPage Resources 105 standard format used when localizing Java-based applications XPages and the resource bundle are explained in Chapter 15, “Internationalization.” Listing 4.52 demonstrates how to load a resource bundle where the source is a file associated with the Domino application It also shows how to reference a value from within the properties bundle (run this to get a free Irish lesson) Chapter 15 covers the use of dojo with XPages in detail Listing 4.52 Resource Bundle Sample Dojo Module This complex property conditionallys load Dojo modules Although XPages already provides a nice set of controls, you might want to use some of the additional controls in the Dojo library in your application In this case, you need to add the appropriate module to your page Listing 4.53 demonstrates a sample of the tag Chapter 11 covers the use of Dojo with XPages Listing 4.53 Dojo Module Sample 106 Chapter Anatomy of an XPage Generic Head Resource This complex property provides a way to link to any external resource (For example, you can output a HTML tag into the HTML page generated for an XPage.) HTML authors typically use this for linking to style sheets Listing 4.54 demonstrates how to use the tag to link to a style sheet As you can see, this is a lot less intuitive than using the tag Listing 4.54 Generic Head Resource Sample Metadata Resource This complex property provides a way to output an HTML tag in the head section of the HTML page generated for an XPage Meta tags provide information about the page (such as a page description, keywords, author name, and other metadata) The meta tag is added inside of the HTML tag Listing 4.55 shows how to use the tag to provide description metadata about an XPage If you preview this sample and view the page source, you see the following HTML tag within the generated HTML: Listing 4.55 Metadata Resource Sample Meta-Data Resource Sample Converters Every control that has an associated value optionally needs to be able to convert that value into a format that’s suitable for display to the application users Additionally, if the control allows the user to enter a new value, the control optionally needs to be able to convert the value the user entered into the appropriate data type Controls with an associated value use string values by default, but even if the underlying data value is a string, conversion might still be needed because users should see the data by using the appropriate conventions for their locale When the underlying data type is not a string, conversion must be performed both when the initial values are presented to the user and before the user-inputted value is processed by the application business logic Converters perform these conversions You have already seen converters being used in the date/time picker example—a date/time converter is set on the edit box to handle the date/time conversion Table 4.1 lists all the converter tags, the converter name, and a short description Table 4.1 Converters Tag Converter ID Description xp:convertDateTime Date Time Converts to and from date values xp:convertList List Converts between to and from list values The string representation of the list is the string value of each list item separated by the specified delimiter xp:convertMask Mask Masks the local value xp:convertNumber Number Converts to and from numeric values, including currency and percent values xp:customConverter Custom Provides a way to provide your own logic to convert the data value to and from its string representation 108 Chapter Anatomy of an XPage Listing 4.56 demonstrates how to use each of the converters with a Computed Field: • The Date Time converter is to the German/Germany locale and displays the long representation of the date and time The xp:converter tag allows another converter to be loaded using its converter ID • The List converter is shown converting a JavaScript array to a | delimited string • The Mask converter masks out the first three uppercase characters for the string value • The Number converter converts a random number (between and 100) with two decimal places • The Custom converter converts the string value to the string representation One A custom converter allows you to provide your own conversion logic Listing 4.56 Converter Sample Converters 109 110 Chapter Anatomy of an XPage Validators Every control that can be used to edit a value must have a way to allow the inputted value to be checked for correctness This is the purpose of a validator—you can optionally associate one or more validators with an input control to check that the value the user entered meets certain criteria The validation can be performed as the XPage is submitted and, if the values are invalid, the submit operation is cancelled This saves unnecessary round trips to the server and improves the user experience When validation fails, an error message is presented to the user, allowing him to take corrective action XPages supports special output controls for displaying either the error messages associated with a single control or all the error messages for the entire XPage Table 4.2 lists all the validator tags, the validator name, and a short description Table 4.2 Validators Tag Name Description xp:validateRequired Required Used when a value must be provided xp:validateConstraint Constraint Used when the value must adhere to a convention as defined by the associated regular expression xp:validateDateTimeRange Date Time Range Used when a date value must lie within a specified range xp:validateDoubleRange Double Range Used when a double value must lie within a specified range xp:validateExpression Expression Used when the value must adhere to a convention as defined by the associated computed expression xp:validateLength Length Used when the length of a string value must be constrained to a certain size xp:validateLongRange Long Range Used when a long value must lie within a specified range xp:validateModulusSelfCheck Modulus Self Check Used for numbers with a self-check digit (such as a credit-card number) xp:customValidator Custom Used when custom business logic needs to be provided to validate the value Validators 111 Listing 4.57 demonstrates usage for each validator listed in Table 4.2 Notice that there is no data source associated with this page, but you can still run this sample and see the validators in action If you preview this page and select the Submit button without entering any values, you are prompted with an error message saying, “Value is required,” and the page is not submitted This is because the first validator requires that you enter a valid in the first edit box This is an example of client-side validation in action (that is, the value is validated on the client-side and the page won’t be submitted with invalid values) Performing the validation on the client-side is good from the user perspective, because she doesn’t have to wait for a server round trip before finding out that she hasn’t entered a value correctly It is also good from the server perspective, because valuable server cycles are not taken up processing pages that need to be returned to the user Entering a value allows you to submit the page because only this first edit box is a required value To see the other validators in action, you must enter a value Try entering various values to see how each validator behaves The only validator that does not support client-side validation is the modulus selfcheck validator When you enter an invalid value into the associated edit box, the page is submitted and the error is displayed when the page is redrawn The xp:message tag displays any error messages associated with a specific control To see all the error messages for the entire page, the xp:messages tag is used Listing 4.57 Validator Sample continues 112 Listing 4.57 Chapter Anatomy of an XPage (Continued) Validators 113 continues 114 Listing 4.57 Chapter Anatomy of an XPage (Continued) continues 116 Chapter Listing 4.57 Anatomy of an XPage (Continued) to ‘baz’”); } }]]> Validators 117 TIP There are occasions where using client-side validation is not what you want So you can disable this for a particular edit control using the disableClientSideValidation property, set this to true to disable client-side validation To disable client-side validation for the entire page, don’t use the xp:eventHandler tag to submit the page—if using a button to submit, change its type to submit To disable client-side validation for the entire application, go to the application properties and set Client Validation to off To disable client-side validation for the entire server, change the server xsp.properties file Figure 4.15 shows how the page behaves when client-side validation is not being used Figure 4.15 Validation failing 118 Chapter Anatomy of an XPage For your interest, to get the page to submit with no errors using the values shown, see Figure 4.16 Figure 4.16 Validation passing Simple Actions Simple actions provide a simple way to add business logic to an XPage without the need to write any code They perform common actions, such as opening a page, setting a value, deleting a document, and so on Their behavior can be simply configured by changing their parameters Simple actions are covered in Chapter In this section, the tags are listed with a brief description, and the syntax for using simple actions is shown and explained Table 4.3 lists all the simple action tags and briefly describes their purposes Table 4.3 Simple Action Tags Tag Name Type Description xp:changeDocumentMode Change Document Mode server Changes the access mode for the document to one of: read only, edit, auto edit (i.e edit mode if user has sufficient rights) and toggle (if in edit mode, change to read-only and vice versa) Simple Actions Table 4.3 119 Simple Action Tags Tag Name Type Description xp:confirm Confirm Action server Presents the user with a message and options to allow execution to continue or stop xp:createResponse Create Response Document server Creates a response document and opens the specified page to edit it xp:deleteDocument Delete Document server Deletes the current document and opens the current page xp:deleteSelectedDocuments Delete Selected Documents server Deletes the documents selected in a view after first prompting the user to confirm this action xp:executeClientScript Execute Client Script client Executes a client-side script xp:executeScript Execute Script server Executes a server-side script xp:modifyField Modify Field server Modifies a field in the current document xp:openPage Open Page server Navigates to a specific page where you can set the document ID of an existing document that can be opened for reading or editing xp:publishValue Publish Component Property client Publishes the value for a component event xp:publishViewColumn Publish View Column client Publishes the value of a view column as a component event 120 Chapter Table 4.3 Anatomy of an XPage Simple Action Tags Tag Name Type Description xp:save Save Data Sources server Saves all the data sources in the current page and optionally navigates to another page xp:saveDocument Save Document server Saves the current document xp:setComponentMode Set Component Mode Action server Changes the mode of a component to either view, edit, or help mode xp:setValue Set Value server Sets the value of a computed expression xp:actionGroup Action Groups server Executes a group of simple actions Some of the simple actions refer to the current document, which means the nearest Domino document to the action You saw earlier in this chapter that an XPage can contain multiple Domino documents, and each can be referenced by name using the value of its var property The current document can be referenced by an implicit variable called currentDocument Listing 4.58 contains two Domino documents: one associated with the view and one associated with a panel Two Computed Fields are both bound to the variable currentDocument, which displays a string representation of the value of that variable (In this case, it is the Java class name and hash code of the associated Java object.) When you run this sample, you see that the values displayed by each Computed Field is different, which means that the Domino document being referenced changes In this case, the Domino document referenced by the first Computed Field is the document associated with the view The second Computed Field references the document associated with the panel Listing 4.58 Current Document Sample Simple actions are associated with the event properties of a control, which means that, when the corresponding event is triggered, the simple action is executed Listing 4.59 demonstrates the set value simple action being used to set a view scope (limited to the lifetime of the XPages view) variable to the value Some Value The simple action is executed once, after the page loads A Computed Field on the XPage is also bound to the same variable and displays the value When you run this sample, you see the string Some Value displayed on the page Listing 4.59 Simple Action Sample 122 Chapter Anatomy of an XPage Multiple simple actions can be grouped and executed together by using action groups Action groups can be nested and have conditions that allow you to build up an execution hierarchy Listing 4.60 demonstrates using action groups to create a simple calculator that can perform addition and subtraction The sample contains edit boxes that allow you to enter the values to use in the calculation and buttons to specify the operation you want to execute When you select the = button, the action group that executes will execute one of two child action groups The first is used when the operation is subtraction, and the second when the operation is addition Listing 4.60 Action Group Sample Simple Actions 123 As well as making execution conditional based on some computed value, you can also make execution conditional on the user agreeing to proceed The confirm simple action can prompt the user before proceeding with an execution In Listing 4.61, the confirm simple action is used within an action group This causes some client-side JavaScript to execute when the user clicks the button The specified message, such as “Add some more?,” displays with OK and Cancel options If the user chooses OK, the page is submitted, the next action executes, and otherwise no further action occurs The simple actions for deleting a single document or multiple documents have this confirmation built in Client-Side Scripting Listing 4.61 125 Confirm Sample Client-Side Scripting Earlier, you saw how to add a script library to an XPage, which is the most common approach to including client-side JavaScript Two additional tags can be used for client-side scripting: • The xp:scriptBlock tag (Script Block) can be used to include a block of JavaScript code at a specified location in the page 126 Chapter Anatomy of an XPage • The xp:handler tag (Event Handler) is used to add an event handler to a control This tag is used in conjunction with the xp:eventHandler to set its handlers property, meaning that you must create an xp:this.handlers tag as a child of xp:eventHandler and make the xp:handler a child of this, as shown in Listing 4.62 Listing 4.62 demonstrates how to include two JavaScript functions in a script block and how to call those functions in response to the onclick event from a button (Chapter 11 covers client-side JavaScript scripting in depth.) Listing 4.62 Client-Side Scripting Sample HTML Tags The next group of tags add some fundamental HTML tags to the displayed page Table 4.4 lists the tags, their name, and a short description You can also type text and HTML directly into the source view of an XPage to add arbitrary markup to an XPage Table 4.4 HTML Tags Tag Name Description Line Break Inserts a line break at the specified point in the XPage Span Content Inserts an HTML span at the specified point in the XPage Paragraph Inserts an HTML paragraph at the specified point in the XPage Listing 4.63 demonstrates the use of these tags and how to add the equivalent markup directly to an XPage One of the main reasons that you might favor the XSP tags or plain passthrough HTML is that you can manipulate the XSP tags by using server JavaScript (In the example shown, the rendered property is being set using a JavaScript-computed expression This allows you to easily show/hide the XSP tags using server logic.) 128 Chapter Listing 4.63 Anatomy of an XPage HTML Sample This is a XSP span This is a XSP paragraph This is a HTML span This is a HTML paragraph Conclusion This concludes your lesson on the basics of the XSP language Don’t worry if you haven’t fully mastered all the tags covered; at this point, the important thing is to look at the source for a simple XPage (like the samples provided in this chapter) and to read the source and begin to understand what the page will Being able to use source mode to read and write XSP is a key skill that you need to master XPages and the XSP programming language In the next chapter, XPages is explored at a deeper level, and you learn about its JSF foundations If you want to stick with pure XPages programming for now, feel free to temporarily skip the next chapter But, you are strongly urged to read at least the section on the JSF processing model in the next chapter before moving on, because it provides some critical insight into how XPages are processed on the server C H A P T E R XPages and JavaServer Faces As mentioned in the beginning of this book, XPages evolved from a previous runtime technology called XFaces XFaces was conceived as a way for IBM to provide a universal user-interface programming model that could be adopted across its diverse portfolio of application development platforms As a runtime technology, it needed to cater to developers of differing skill sets, such as Java/J2EE developers, Domino developers, and so forth These categorizations are not mutually exclusive, and many organizations contain developers with both sets of skills who might be working on the same projects In fact, many such developers want to choose which tools to use based on the task they need to accomplish at any given time (For example, they might need to rapidly create a user interface using a WYSIWYG tool and then switch to using Java to add some complex business logic.) What IBM set out to achieve with XFaces was to define a programming model that would be suitable for a so-called script-level developer, such as someone who knows how to program using a markup language and JavaScript This programming model was intended to allow developers to target multiple platforms, such as web and the Eclipse Rich Client Platform (RCP) Also, this programming model was based on the JavaServer Faces (JSF) standard-based web application development framework Achieving this goal would provide the following benefits to application developers: • Learn Once, Write Anywhere: Developers need only learn one model for development across these platforms The model must be flexible and powerful to allows programmers to fully exploit and optimize the UI for any particular platform • Write Once, Run Anywhere™: Developers can create a single set of artifacts that can run across multiple platforms 129 130 Chapter XPages and JavaServer Faces • Provide a script-based programming model: A model that would be familiar for developers with a Domino Designer (or similar) and dynamic HTML programming background (no Java skills required) • Allow artifacts to be shared between Java and Script developers who work on the same project: For example, script developers create the frontend user interface and Java developers create the backend business logic • Flexibility: Allows developers to use the most appropriate tool for the task they perform As XFaces morphed into XPages, these design points were all retained This chapter examines the relationship between XPages and JSF Although one of the goals in XPages is to hide all the Java and J2EE-centric aspects of the JSF programming model, having an understanding of the underlying technology is a major asset for any XPages developer By understanding how JSF works, and especially the workings of the JSF lifecycle, you learn how your XPages are processed as your application executes This helps understanding why your application behaves in a particular fashion Also, both XPages and JSF are designed to be extended For the Domino Developer, you are no longer restricted to what is provided within the platform as delivered by IBM; it’s now possible to extend the platform either to solve a particular problem or as a way to start a new business This chapter is aimed at developers who are interested in extending the XPages runtime using Java by creating new XSP components or developers who are coming from a J2EE background and want to understand how XPages extends JavaServer Faces This chapter uses the standard JSF terminology when explaining how JSF works and the relationship between JSF and XPages In JSF parlance, a component is a UI element or what has been previously referred to as a UI control (an edit box or button) JSF also uses the terms view and component tree interchangeably XPages also uses view (remember the root tag of every XPage is the xp:view tag) and an XPages’ view is, in fact, a component tree Knowing this means the working definition of XPages can be extended to this: XPages is an XML-based language that can be used to define JSF views, and an XPage is a static representation of a JSF component tree Be sure to download the chapter5.nsf files provided online for this book to run through the exercises throughout this chapter You can access these files at www.ibmpressbooks.com/ title/9780132486316 What Is JavaServer Faces? JSF is a component-based, user interface framework for building Java-based web applications The framework provides the following capabilities: • A set of reusable user-interface components that can be used to easily create an application frontend or can be used as the starting point to create new custom user interface components JSF Primer 131 • A Model-View-Controller (MVC) programming model that supports event-driven programming • A state-full server representation of the user interface that can be synchronized with the client representation • A mechanism to allow data flow to and from the user interface, including the capability to perform data conversion and data validation • A framework that can be extended using Java programming techniques Using the JSF framework as the starting point when creating a web application frees the application developer from having to deal with the stateless nature of HTTP—without the use of a framework, no application state is maintained on the server between requests The developer can create the required user interface using the standard UI components (a.k.a controls) provided by JSF Then, the developer can bind these controls to the application data (in the form of Java beans) and then trigger server-side business logic in response to user actions on the application user interface A Java bean is a reusable Java-based software component (see http://java.sun.com/developer/ onlineTraining/Beans/bean01/index.html for more details) This type of programming model is familiar to developers of rich client-based applications using technologies such as the Standard Widget Toolkit (SWT); however, at the time JSF was introduced, it was pretty much a new concept for web developers The following JSF Primer sidebar provides a basic introduction to JSF and is written with the assumption that you have no knowledge of Java2 Enterprise Edition (J2EE) The relevant J2EE concepts are briefly explained in this sidebar The JSF lifecycle is also explained in the sidebar; this is a key concept that all XPages developers should understand For a detailed look at the JSF technology, the authors recommend the following resources: • JavaServer Faces Specification, version 1.1 (http://java.sun.com/javaee/javaserverfaces/ reference/api/) • JavaServer Faces (O’Reilly) • Mastering JavaServer Faces (Wiley) JSF Primer To run a JSF-based application, you need a Java web container, such as an Apache Tomcat server, and an implementation of the JSF specification (Sun Microsystems provides a reference implementation available here: http://java.sun.com/j2ee/javaserverfaces.) A Java web container is a Java-based server for running Java web applications JSF 1.1 requires a web container that implements, at a minimum, the Servlet 2.3 and JavaServer Pages 1.2 specifications (XPages requires support for the Servlet 2.4 specification.) IBM WebSphere Application Server (WAS) and Portal Server support the Servlet and JSP specifications 132 Chapter XPages and JavaServer Faces A servlet is a Java class that runs in the web container, processes client requests, and generates responses A servlet is passed parameters that represent the request and response and, in simple cases, all the processing logic can be included within the servlet Typically, a servlet is defined as the entry point or front controller for a web application A servlet typically delegates to request handlers to process the client requests and a presentation tier to generate the responses Listing 5.1 shows the source code for a simple HTTP servlet This servlet handles an HTTP GET request and responds with a HTML page that displays the text Hello World The code to handle the request has access to a request object, which can be used to retrieve information about the request being processed and a response object, which can be used to write the response that is returned to the client Listing 5.1 Sample HTTP Servlet package mxp.chap05; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Sample Servlet */ public class SampleServlet extends HttpServlet { /** * Handle a HTTP GET request */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(“text/html”); PrintWriter out = response.getWriter(); out.println(“”); out.println(“”); out.println(“Hello World”); JSF Primer 133 out.println(“”); out.println(“”); out.println(“Hello World”); out.println(“”); out.println(“”); } } JavaServer Pages (JSP) is a presentation logic layer that can generate HTML pages in response to client requests A JSP page looks like a HTML page, but it contains a mix of static HTML and JSP directives, which can be used to generate dynamic content or performing some processing associated with generating the client response JSP uses tag libraries to allow special tags to be declared, which can then be invoked by the JSP engine A JSP implementation comes with a standard tag library called the JavaServer Pages Standard Tag Library (JSTL) Listing 5.2 shows a sample JSP page that uses the JSF tag library to embed JSF components within an HTML page Based on what you have learned so far about XSP markup, this sample should be readable It contains a mix of HTML and JSF tags The JSF tags cause JSF components to be created and results in a HTML form being created, which contains an edit box that can be used to enter a value and a button that can be used to submit the form Listing 5.2 Sample JSP with JSF Tags Enter some value: JSP is the default presentation tier used by the JSF reference implementation The presentation tier is the layer in an application framework that is responsible for displaying the application data in a human-readable format The presentation tier defines the JSF component tree (also known as the JSF view), which is the hierarchy of controls that is presented in the user interface A typical 134 Chapter XPages and JavaServer Faces starting point for a JSF-based application is where a user requests a JSP, such as typing a URL like this into a browser: http://somehost/jsfapp/somepage.jsp This causes the JSP engine to load and execute the specified JSP If this page contains JSF components (using the standard JSF tag library), a JSF component tree is also created in addition to the regular JSP processing (the JSF tags are responsible for creating the JSF component tree) The JSF components generate the HTML markup that is presented to the user and the view is cached for the user (see section 2.1.1 of the JSF 1.1 specification, “Non-Faces Request Generates Faces Response”) Now, if the same page is submitted back to the server, it is handled by the JSF servlet This servlet is part of the JSF implementation and acts as a front controller for all JSF-based applications JSF requests are processed in accordance with the rules defined by the JSF request processing lifecycle The JSF request processing lifecycle consists of a number of well-defined phases that describe how each request is handled and, of course, these phases also apply to XPages The phases on the standard request processing lifecycle are as follows: Restore View Apply Request Values Process Validations Update Model Values Invoke Application Render Response Figure 5.1 illustrates how the processing lifecycle operates The Restore View phase retrieves the JSF view for the request If no JSF view exists, a new one is created and cached for later use Maintaining a consistent representation of the JSF view between requests simplifies the programming task for the application developer by simplifying the application logic to focus on the business problem and not having to maintain information about the state of the view The Apply Request Values phase is used to allow the JSF components to update their state based on the values from the current request; for example, if the component represents an editable value, the component stores the current value Action and editable components have a special behavior during this phase If the component immediate property is set to true, the JSF lifecyle is short circuited For an action component, the action processing happens at the end of this phase instead of during the lifecycle For an editable component, the validation processing happens immediately The Process Validations phase allows any validators associated with components in the view and any built-in validation associated with a specific component to be executed All components that can be used to edit a value and support validation, have an associated property (aptly JSF Primer 135 named valid) to indicate whether the current value is valid When validation errors occur, messages are queued and the valid property of the associated component is set to false Validation error messages can displayed to the end user using the xp:message or xp:messages tags as described in Chapter 4, “Anatomy of an XPage.” Validation errors typically cause the lifecycle processing to terminate and result in a response being immedeatly sent back to the end user Response Complete Faces Request Restore View Apply Request Values Process Events Response Complete Process Validations Process Events Render Response Response Complete Faces Response Render Response Process Events Response Complete Invoke Application Process Events Update Model Values Conversion Errors/ Render Response Validation/Conversion Errors/Render Response Figure 5.1 JSF request processing lifecycle If the Update Model Values phase is reached, it is assumed that the values provided in the request are valid (as defined by any validators specified in the view) The current values are stored in the localValue property of the associated component During this phase, the application data is updated with the new values In the case of an XPages application, the values are written to the Domino document during this phase If the Invoke Application phase is reached, it is assumed that the application data has been updated The relevant application logic specified in the view is executed during this phase In an XPages application, if application logic is associated with a button and that button caused the page to be submitted, it is now that the logic is executed The Render Response phase generates the response and to saves the state of the view In the XPages case, the response is an HTML page and the rendering is performed using a platformspecific renderkits, and the application developer has control over the state saving (for example, to optimize server performance, he can decide not to save any state) The JSF response rendering model is flexible and is discussed further 136 Chapter XPages and JavaServer Faces From Figure 5.1, you see that, after certain phases, there is an event-processing operation that can result in the lifecycle being short circuited and the response being rendered This typically happens if there is a conversion or validation error, which means that data specified by the end user is not valid, so it doesn’t make sense to update the application data or to execute any application logic Numerous other key concepts in JSF are important to understand before looking at how XPages builds on top of this foundation: Integration with JSP User Interface Component Model Value Binding and Method Binding Expression Evaluation Per-Request State Model Application Integration Rendering Model JSF APIs JSF implementations must support JSP as the page-description language (the mechanism for defining the JSF component tree) This allows J2EE developers to start creating JSF-based applications using a well-known technology When JSF tags are added to a JSP page, they cause the JSF component tree to be created when the page is executed A JSF user interface is created as a tree of components (known as controls in XPages) Components typically are rendered to the user as HTML markup, which produces the application interface However, not all components render as visual elements in the UI; they can render no markup or just client-side JavaScript and thereby add behavior to the UI Components can be manipulated on the server, and this can result in changes to the application UI (the Button sample in Chapter shows an example of this) Components can have different types, such as have the ability to trigger application logic, can be a container for other components, can have an associated value, or can edit its associated value A well-defined data conversion model associated with components allows application data to be converted between the underlying data types and string values and back again This is essential as data is going to be represented as string values in the HTML markup There is also a well-defined validation model that allows multiple checks to be performed on user input and prevents application logic executing on invalid data JSF implementations provide a standard set of user interface components, and these form the basis for the controls you can add to an XPage Finally, a standard set of data model classes can be used with the standard controls; refer to the JSF Java documentation for the javax.faces.model package for more information (http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/) Binding expressions are how application logic and data binding is performed in JSF Value bindings are used when you need to compute a component property or when you want to bind application data to a component for display and\or editing JSF uses Expression Language (EL) to specify value binding expressions EL is fully defined in the JavaServer Pages specification (version 2.0) and the JSF usage only differs in the delimiters used, such as #{ and } instead of JSF Primer 137 ${ and } and the fact that EL functions are not supported EL can be used in XPages applications, as demonstrated in examples in Chapter Method-binding expressions are a variation on value bindings where parameters can be passed to the method being invoked and the result can be returned Method bindings invoke application logic, which in JSF applications is code in Java XPages additionally supports application logic written in JavaScript JSF supports an extensible mechanism for resolving binding expression variables and properties By default, JSF supports Java beans-based property resolution and a well-defined set of variables This Java-centric approach has been extended in XPages to better support the use of JavaScript and Domino During the JSF request processing lifecycle, the request state is represented by a set of JSF objects, such as FacesContext, FacesMessage, ResponseStream, ResponseWriter, and FacesContextFactory JSF provides a mechanism to allow built-in request related objects to be available during request processing The JSF programming model is Java-based, and there is a well-defined model for the execution of the JSF-based application XPages provides a dynamic HTML-like programming model (combination of JavaScript and Markup Language) on top of JSF This can be achieved because JSF provides an extensible mechanism to modify the exeution of a JSF application The application integration APIs in JSF provide access to modify the behavior of how JSF-based applications are executed During the execution of a JSF request, the incoming request values need to be decoded at the start of the lifecycle during the Apply Request Values phase and subsequently encoded when the response is generated JSF allows each component to handle the decoding and encoding processes directly One disadvantage with this approach is that it can tie a component to a particular platform or rendering technology, such as a component that decodes HTTP requests and encodes HTML responses that can’t be used with a VoiceML client To address this problem, JSF supports a model where each component can delegate the encoding and decoding processes to an associated renderer Now, different renderer implementations can be provided for different client types, and JSF provides a simple mechanism to group these renders into a renderkit along with the ability to switch between renderkits This keeps the components platform independent JSF provides a default HTML renderkit The JSF reference implementation comes in two parts: JSF API JSF Implementation The JSF API is a Java API that consists of interfaces and abstract classes that define the abstractions that make up the JSF engine JSF allows key parts of the implementation to be extended while still preserving the default behavior This is achieved by means of a delegation model, where the new extension has the option to execute first and then delegate to the default implementation when appropriate The JSF API provides abstract Java classes for the modules, which can be extended JSF also has an XML configuration file format and a mechanism for loading multiple instances of this file To override a module in the JSF engine, you need to provide 138 Chapter XPages and JavaServer Faces your custom implemntation and a Faces configuration XML file that specifies that your implementation should be loaded and used instead of the default one Consider the following quote from the JavaServer Faces specification: JSF’s core architecture is designed to be independent of specific protocols and markup However it is also aimed directly at solving many of the common problems encountered when writing applications for HTML clients that communicate via HTTP to a Java application server that supports servlets and JavaServer Pages (JSP) based applications Although JSF is Java-centric and J2EE-based, the API provides sufficient flexibility to allow the JSF framework to be used in other contents So, it is possible to create a non Java-centric programming model on top of JSF and still maintain the benefits of providing a standardsbased solution, and this is what has been achieved in XPages How Does XPages Extend JSF? As previously mentioned, JSF provides a delegation model whereby key modules in the JSF engine can be replaced To this, you need to create your own Java class that extends the base class, which defines the module you want to extend This class must have a constructor that takes a single argument, which is an instance of the class defining the module you are extending A concrete example of this would be the custom variable resolver that is provided in XPages The default variable resolver in JSF provides access to a number of built-in variables (see Table 5.1) Table 5.1 JSF Default Variables Name Value applicationScope Map containing the application scope values Cookie Map containing the cookies for the current request facesContext The FacesContext instance for the current request Header Map containing the HTTP header values for the current request headerValues Map containing arrays that contain the header values for the HTTP headers for the current request initParam Map containing the initialization parameters for the web application Param Map containing the request parameters for the current request paramValues Map containing arrays that contain the parameter values for request parameters for the current request requestScope Map containing the request attributes for the current request How Does XPages Extend JSF? 139 Name Value sessionScope Map containing the session attributes for the current request View UIViewRoot of the current component tree XPages extends these variables to include some additional ones, which are relevant for a Domino application developer, such as the current database JSF provides a pluggable mechanism to allow what is called a variable resolver to be configured for a JSF application This variable resolver must provide the default behavior as defined in the JSF specification but can provide additional functionality To this, the following two steps are required: An implementation of javax.faces.el.VariableResolver must be provided It either must implement the default behavior or else delegate to the default implementation The faces-config.xml file for the JSF application must be edited to specify the new variable resolver implementation The faces-config.xml file is the main configuration file for a JSF-based application It is used to configure the behavior of the application and the JSF runtime You need to switch to the Java perspective in Domino Designer to perform both of these steps The faces-config.xml file is located in the \WebContent\WEB-INF folder Listing 5.3 shows the Java code for a variable resolver, which adds support for an additional variable called “magic,” which resolves to a string value “Abracadabra.” This class provides a constructor that takes a single variable, which is an instance of VariableResolver; this delegate provides the default behavior The custom implementation can delegate to this and still provide the default behavior and be compliant with the JSF specification Listing 5.3 Sample Variable Resolver package mxp.chap05; import java.util.logging.Logger; import javax.faces.context.FacesContext; import javax.faces.el.EvaluationException; import javax.faces.el.VariableResolver; /** * Sample variable resolver */ (continues) 140 Chapter Listing 5.3 XPages and JavaServer Faces (Continued) public class SampleVariableResolver extends VariableResolver { private VariableResolver delegate; /** * Constructor which takes delegate VariableResolver */ public SampleVariableResolver(VariableResolver resolver) { delegate = resolver; } /** * Return the object associated with the specified variable name */ public Object resolveVariable(FacesContext context, String name) throws EvaluationException { if (“magic”.equals(name)) { return “Abracadabra”; } return delegate.resolveVariable(context, name); } } To get this instance to load, an entry must be added to the faces-config.xml specifying that this class as the variable resolver Listing 5.4 shows what this entry looks like in the facesconfig.xml Listing 5.4 Variable Resolver Configuration mxp.chap05.SampleVariableResolver by IBM Lotus Domino Designer Do not modify.—> How Does XPages Extend JSF? 141 After these two changes are made, you can now reference the “magic” variable from the SampleVariableResolver XPage Listing 5.5 shows the XSP markup that contains Com- puted Fields that reference the new “magic” variable Listing 5.5 Variable Resolver Sample XPage When you preview this page, you see the results illustrated in Figure 5.2 Figure 5.2 Variable resolver sample preview TIP The preceding example explains one of the mechanisms that XPages uses to extend JSF XPages is currently built on top of JSF 1.1; however, in JSF 2.0, the VariableResolver class has been deprecated in favor of a new class called ELResolver XPages might be updated to use JSF 2.0 (or later) in the future So, if you bypass the XPages programming model and use the JSF classes directly, check the JSF 2.0 documentation so you understand the implications Deprecated APIs continue to be supported, but the best practice is to upgrade your code to the newer API The key message is that, although the XPages programming model is supported consistently from release to release, when you opt to go direct to JSF, you need to consider future compatibility XML-Based Presentation Tier As mentioned earlier, the default presentation tier in JSF version 1.1 is JSP There are well-known issues with using JSP and JSF, but the biggest hurdle from the Domino developer perspective is that JSP is a Java-based technology, and not all Domino developers are familiar with Java Domino developers are, however, familiar with creating HTML markup and, therefore, it was decided to create a new markup-based presentation for JSF Additionally, JSF developers use the faces-config.xml file to configure certain aspects of their application, such as navigation rules and managed beans In designing the new presentation tier, it was decided to allow the developer to perform most of the application configuration within the XPage itself including page 142 Chapter XPages and JavaServer Faces navigation, the configuration of data sources, and the inclusion of business logic This new presentation tier became the XSP language JSF provides the capability for a custom implementation to be provided for the Render Response and Restore View phases of the JSF lifecycle An abstract Java class called ViewHandler can be extended and then this new implementation configured to be the view handler for the JSF application (as demonstrated previously with the custom navigation handler) This mechanism is used in XPages to provide the XSP markup-based presentation tier So, the first and most important enhancement that XPages provides on top of JSF is the capability to create the JSF view using a markup language Additionally, XPages provides some custom options for the Restore View phase The default behavior for saving the state of the JSF view is to walk the component tree and request that each component save its state The state data is then either stored on the server or serialized into the HTML response and stored on the client Saving view state on the server has performance implications for the server Saving state in the response increases the size of the response and, therefore, increases the network traffic In some cases, there is no need to store the full state of the view (for example, when the page is being used for display only) Request Processing Lifecycle XPages allows you to execute the JSF request processing lifecycle on a portion of the component tree To this, use the execMode and execId properties of the event handler The execMode property allows you to specify that either the complete or partial execution of the lifecycle When partial execution is specified by setting execMode=”partial”, only a portion of the component tree is used when executing the lifecycle Components that are not part of this subtree are not processed during the lifecycle The execId property specifies the component ID of a control within the pages component tree, which is the root of the subtree to be used when executing in the lifecycle This allows you to optimize the execution of the lifecycle as a much smaller number of components need to be processed This is something you will want to to decrease the load on your server and to improve the performance of your XPages XPages also provides an optimization for the Render Response phase of the lifecycle, which either limits or eliminates the response The event handler has two properties—refreshMode and refreshId—which specify and control partial refresh (partial or no rendering of the response) When partial refresh is specified by setting refreshMode=”partial”, only a portion of the component tree contributes to the generated response The response can also be completed eliminated by setting refreshMode=”norefresh” The refreshId is used in conjunction with a partial refresh to specify the portion of the component tree, which is used to generate the response, the specified control ID, which be the root of the subtree that is used Partial or no refresh is another optimization technique The responsiveness of your XPages and the end user’s experience can be significantly improved by using partial refresh to update just a part of the page and to reduce the number of page reloads How Does XPages Extend JSF? 143 User Interface Component Model JSF uses the term component to refer to user interface components or what are known as controls in XPages These components are the user interface elements used to create the application user interface JSF provides the following: • A fundamental API for user interface components • Component behavioral interfaces that allow components to provide specific functionality, such as access to a data model • A facility to convert data values (for example, to string representation for use in the presentation tier) • A facility for validating user input XPages builds on top of the JSF user interface component model to provide the following: • XPages behavioral interfaces that allow components to contribute to the XPages-specific pages • XPages converters, which extend the default conversion facility provided by JSF • XPages validators, which extend the default user validation provided by JSF XPages Behavioral Interfaces The behavioral interfaces are implemented by user-interface components that support XPages-specific behavior For example, in regular JSF, you must add a tag corresponding to a form component in the view definition to have a HTML form rendered in the response For convenience, the standard XPages view root component automatically adds a form to each XPages view But, what happens now if you want to manually add the form yourself? When you this, the standard XPages form component automatically disables the automatic form creation by finding the parent, which creates the form and tells it not to automatically create a form This list describes the XPages behavioral interfaces: • FacesAjaxComponent: Implemented by user-interface components that can handle an AJAX request and return a valid response The type-ahead component implements this interface and returns the list of suggestions in XML format as the response to an AJAX request • FacesAutoForm: Implemented by user-interface components that automatically create a form component and is used to ensure that when a form is manually inserted into the view that an automatic form is not created The XPages view root component implements this interface and normally automatically creates a form for each XPage • FacesComponent: Implemented by user-interface components that need to perform some initialization before and/or after their children are created or want to build their own children The repeat component implements this because it builds its own children 144 Chapter XPages and JavaServer Faces The repeat container component (which is the parent for each row of children in a repeat) also implements this interface to ensure the correct row data is available to its children as they are being created • FacesDataIterator: Implemented by user-interface components that iterate over a value and is used to get information about the data model being used and the rows of data that is displayed The repeat component implements this • FacesDataProvider: Implemented by user-interface components that can be configured with a data source The view root implements this and can be configured with a Domino document or view data source • FacesInputComponent: Implemented by input components and is used to disable validation and to disable the behavior in the Notes client where the user gets prompted if a value is modified and might need to be saved before closing an XPage The XPages standard input component (described in the next section) implements this interface • FacesInputFiltering: Implemented by input components that support input filtering and find the correct input filer to be applied The XPages standard input component implements this interface and supports the filtering of active content • FacesNestedDataTable: Implemented by user-interface components that render using multiple tables and is used to support AJAX requests that replaces the component rendering The XPages standard view panel component (described in the next section) implements this interface • FacesOutputFiltering: Implemented by output components that support output filtering and is used to find the correct output filter to be applied The XPages standard output component (described in the next section) implements this interface and supports the filtering of active content • FacesPageIncluder: Implemented by user-interface components that include another XPage and need to perform some initialization before and/or after their children are created or want to build their own children The include component implements this interface because it is used to include another XPage The standard include composite component (described in the next section) also implements this interface because including a Custom Control is a special case of including another XPage • FacesPageProvider: Implemented by user-interface components that act as the root of a page during the create view phase of the JSF lifecycle This is only intended for internal use by the XPages page-loading mechanism and must never be implemented by a third party • FacesParentReliantComponent: Implemented by user-interface components that have a strict child/parent relationship and does not behave correctly if an additional container is inserted between them, and their parent and is used with Custom Controls to force the include composite component to remove itself when the children of the Custom How Does XPages Extend JSF? 145 Control all rely on the parent The XPages select item component implements this because it depends on its parent to render the selection it represents • FacesPropertyProvider: Implemented by the include composite component and used in the publishing of composite data This must not be implemented by third parties • FacesRefreshableComponent: Implemented by user-interface components that can be refreshed by one of its children in response to an Ajax request If the component changes its client ID while rendering its children (this is allowed for a NamingContainer), the child uses the wrong client ID and the refresh fails This interface allows the child to get the correct client ID for use in a partial refresh The XPages standard data component implements this interface • FacesRowIndex: Implemented by user-interface components that support a row index and is used by data sources to compute the components bean ID The XPages standard data component implements this interface • FacesSaveBehavior: Implemented by action components which support the save property and is used to check if the data source son the page should be saved after the corresponding action is performed The XPages standard command component (described in the next section) implements this interface • FacesThemeHandler: Implemented by user-interface components that handle setting their own default styles The XPages standard file download component implements this interface • FacesDojoComponent: Implemented by user-interface components that support Dojo attributes The XPages type-ahead component implements this interface • FacesDojoComponentDelegate: Implemented by user-interface components that support Dojo attributes on behalf of another component The XPages date time helper component implements this interface • ThemeControl: Implemented by user-interface components that support style kits The majority of the XPages components support this You could use the behavioral interfaces if you decide to extend XPages (for example, by building your own Java components for XPages) This subject is covered in Chapter 12, “XPages Extensibility.” XPages Converters JSF defines a mechanism to perform conversion to and from the string representation of the data model value Model values need to be converted to a string representation to be displayed for the user and, when the user edits a value, it is received as a string value and needs to be converted to the correct type for the underlying data model The javax.faces.convert.Converter interface defineS the converter behavior JSF provides a standard set of converters for common data types: various number formats and date\time values XPages extends two of the standard converters and provides one new converter implementation: 146 Chapter XPages and JavaServer Faces • DateTimeConverter: The XPages data/time converter extends the standard JSF date/time converter, but it uses the International Components for Unicode (ICU) libraries for the conversions For more information on ICU, visit http: //site.icu-project.org • MaskConverter: The XPages mask converter applies the specified mask to the string representation of the value being converted Table 5.2 shows a table listing the supported mask characters • NumberConverter: The XPages number converter handles the fractional part of integers and can handle the result of XPath Table 5.2 Mask Characters Mask Character Description # Any valid decimal digit number (uses Character.isDigit) ‘ Used to escape any of the special formatting characters U All lowercase letters are mapped to uppercase (uses Character.isLetter) L All lowercase letters are mapped to uppercase (uses Character.isLetter) A Any valid decimal digit or letter (uses Character.isDigit and Character.isLetter) ? Any letter * Anything H Any valid hex character (0–9, a–f or A–F) XPages Validators JSF defines a mechanism to provide the validation (checks) of user inputted values Multiple checks can be performed on a single value The javax.faces.validator.Validator interface defines the validator behavior Again, JSF provides some standard validators for checking that numbers or strings lie within a specific range XPages provides some additional validators and some additional interfaces to customize the validator behavior The following list describes the XPages validators in detail: • ClientSideValidator: Implemented by validators that support client-side validation Validators that support client-side validation are asked to provide a single line of JavaScript to be included in the rendered response For XPages validators, this JavaScript references the xspClientDojo.js library and emits a call to the appropriate validator method Listing 5.6 shows the JavaScript that gets included in a page that How Does XPages Extend JSF? 147 contains an edit box with a length validator and a submit button Note the call to attach the length validator to the input control in the HTML page; this associates the length validator with the edit box whose contents it needs to validate Listing 5.6 Length Validator Client-Side JavaScript XSP.addOnLoad(function() { XSP.attachValidator(“view:_id1:inputText1”,null,null,new XSP.LengthValidator(0,5,”Incorrect length”)); XSP.attachEvent(“view:_id1:_id4”, “view:_id1:button1”, “onclick”, null, true, false); }); • FacesRequiredValidator: Implemented by the required validator and used by the XPages standard input component to identify if a required validator has been added to its list of validators • ConstraintValidator: Validates using the specified regular expression or, if the regular expression is set to one of the predefined keywords, performs the associated standard validation Table 5.3 shows the predefined keywords the constraint validator supports Table 5.3 Predefined Constraint Checks Regex Description Alphabetonly Checks if the value contain only letter characters Digitonly Checks if the value contain only number characters AlnumOnly Checks if the value contain only letter and number characters • DateTimeRangeValidator: Validates that a date value lies within the specified time period Client-side validation and computed properties are supported • DoubleRangeValidatorEx2: Extends the standard JSF validator to support clientside validation and computed properties • ExpressionValidator: Enables you to provide custom logic for the client-side and server-side validation • LengthValidatorEx and LongRangeValidatorEx2: The XPages version of these validators extends the standard JSF validator to support client-side validation and computed properties 148 Chapter XPages and JavaServer Faces • ModulusSelfCheckValidator: Performs a modulus self check (for modulus 10 and 11 only) Client-side validation is not supported A modulus self check is a standard mechanism for validating identification numbers; for example, modulua 10 (or Luhn algorithm) is a single checksum formula used to validate credit-card numbers • RequiredValidator: Checks that a value has been specified Standard User-Interface Components JSF provides a standard set of user interface components which cover the standard control types Each of these components has a well-defined behavior which is platform independent The intention is that the JSF standard components would be extended to provide specific implementations for different client platforms In fact, JSF extends these standard components to provide HTMLspecific components XPages extends the standard components to add XPages-specific behavior and also defines its own completely new standard components XPages then extends these components to provide the specialized XPages user interface components that are used in Domino Designer and supports the browser and Lotus Notes clients Figure 5.3 shows the hierarchy of user interface components If you are going to create your own user interface components you will normally be extending one of the JSF or XPages standard components UIComponent JSF Component Interface UIGraphic, UIData, … UIComponentBase JSF Standard Components UIDataEx, UIFileDownload, … UIComponentBase XPages Standard Components XspInputText, XspSection, … UIComponentBase XPages Specialized Components Figure 5.3 XPages user interface component hierarchy How Does XPages Extend JSF? 149 The following list briefly describes each of the standard user interface components • UICallback: Represents an area in Custom Control where the user of the Custom Control can add additional content This component builds its own contents and, after its children are added, it checks if they are all instances of NamingContainer and, if they are, it removes itself from the component hierarchy • UIColumnEx: Represents a single column of data and expects to have a parent UIData UIColumnEx implements FacesParentRelientComponent to signal this dependency on its parent • UICommandButton: Represents a button that, when clicked by the user, can trigger some application logic • UICommandEx2: Represents a control that, when activated by the user, can trigger some application logic UICommandEx2 implements FacesSaveBehavior, which means that, when triggered, it can cause the saving of all data sources on the XPage • UIComponentTag: An abstract component that is extended by specialized XPages components which represent a tag, such as a div, span, table, and so on • UIDataColumn: Extends UIColumnEx, but currently does not add any new behavior • UIDataEx: Represents a multirow data model The only allowed children are instances of UIColumnEx, which collectively define the presentation a row of data from the model • UIDataIterator: Like UIDataEx, this component represents a multirow data model, but does not have any restriction on what type of children it will have The children process multiple rows of data, but in a free format rather than the tabular format that UIData uses • UIDataPanelBase: Represents a component that organizes the layout of its children and provides data (it implements FacesDataProvider) that is scoped to its children • UIDateTimeHelper: Used to transform an edit box into a date time picker • UIEventHandler: Used to handle events on behalf of its parent It can be configured to handle both client-side events or server-side actions for the component that is its direct parent • UIFileDownload: Represents a control that can be used to download one or more files • UIFileuploadEx: Represents a control and can be used to upload a file from a user to the server • UIFormEx: Represents a HTML form and ensures an XPages doesn’t contain nested forms because of the automatic creation of a form elsewhere in the component hierarchy 150 Chapter XPages and JavaServer Faces • UIGraphicEx: Represents a control that displays a graphical image to the user Currently, the XPages version does not add any new behavior, but it might so in the future • UIInclude: Used to support including one XPage within another • UIIncludeComposite: Used to support including a Custom Control within an XPage • UIInputCheckbox: Represents a checkbox control • UIInputEx: Used for controls that display a value and allow that value to be edited UIInputEx adds support for HTML filtering, disabling the validation, and Dojo • UIInputRadio: Represents a radio button control • UIInputRichText: Represents a rich text edit control • UIInputText: Represents an edit box control • UIMessageEx: Supports the display of error messages for a specific component and adds style kit support • UIMessagesEx: Supports the display of error messages not related to a specific component and adds theme support • UIOutputEx: Used to display data model values to the user and adds HTML filtering support • UIOutputLink: Represents a HTML link • UIOutputText: Displays a computed value • UIPager: Used to display a pager control to allow paging through the rows of data associated with the UIData or UIDataIterator component • UIPagerControl: Used to display one of the buttons in a pager control, such as first, previous, next, or last buttons • UIPanelEx: Used as a base component for the controls that are used include an XPage • UIPassThroughTag: Used whenever a non-xsp tag is added to an XPage There is no associated xsp tag for this component, but it is used by the page loading mechanism and appears in the XPages page-translation source code • UIPassThroughText: Used whenever text added to an XPage There is no associated xsp tag for this component, but it is used by the page loading mechanism and appears in the XPages page translation source code • UIPlatformEvent: Represents a control that can handle a platform event When the specified platform event occurs, the associated script is executed • UIRepeat: This component is a FacesDataIterator and has two modes of operation: It can either use either a single instances of its children (like a UIData component) or it can create one instance of its children for every row of data How Does XPages Extend JSF? 151 • UIRepeatContainer: Used by the UIRepeat component when it is creating multiple instances of its children Each instance of UIRepeats children are nested inside a UIRepeatContainer, and the container provides access to the row data and index • UIScriptCollector: Automatically added to the root of an XPages component tree Its job is to aggregate all the JavaScript code that needs to be included in the generated HTML and to include it within a single script tag at the bottom of the page • UISection: Represents a container control that displays as a section and can be expanded and collapsed • UISelectItemEx: Represents a single selection option for a control that allows the user to select from a number of choices, such as a listbox • UISelectItemsEx: Represents multiple section options for a control that allows the user to select from a number of choices, such as a listbox • UISelectListbox: A listbox control, which will have nested UISelectItemEx or UISelectItemsEx, representing the available choices Depending on whether the listbox is configured for multiple selection, a different specialized XPages component is used, either XspSelectManyListbox or XspSelectOneListbox • UISelectManyEx: Represents a control that allows the user to select multiple values from a number of choices • UISelectOneEx: Represents a control that allows the user to select one value from a number of choices • UITabbedPanel: Represents a control that contains children which are instances of UITabPanel and displays the children as a series of tabs • UITabPanel: Represents a single tab in a tabbed panel control • UITypeAhead: A helper component that is used with an edit box to provide type-ahead functionality, such as the ability for the user to start typing in the edit box and see a list of suggestions • UIViewColumn: Represents a single column in a view control • UIViewColumnHeader: Represents the header for a single column in a view control • UIViewPager: Represents a pager in a view control • UIViewPanel: Represents a view control that can be bound to the data in a Domino view • UIViewRootEx2: The root component of all XPages component hierarchies • UIViewTitle: Represents the title of a view control You could use one the standard user interface components as the base class if you were building your own Java components for XPages This subject is covered in Chapter 12 152 Chapter XPages and JavaServer Faces Value Binding and Method Binding Expression Evaluation JSF supports two types of binding expressions: • Value binding: Computes a value for a property and can support both reading and writing a value • Method binding: Executes come logic Binding expressions are identified using the #{ and } expression delimiters JSF supports Expression Language (EL) for value and method bindings JSF defines the javax.faces.el.ValueBinding abstract class to represent a value binding expression and javax.faces.el.MethodBinding to represent a method binding The JSF application object is responsible for creating instances of these for use in the JSF processing XPages extends support for expression binding to include the following: • Using JavaScript • Using a special syntax to resolve client IDs • Support for multipart expressions • Simple actions JavaScript Binding Expressions A JavaScript binding expression is delimited using #{javascript: and } Listing 5.7 shows an example of a JavaScript value binding expression being used to compute the value for a Computed Field When this code is executed, a string representation of the database property is displayed in the Computed Field Listing 5.7 JavaScript Value Binding Expression Listing 5.8 shows the syntax for the JavaScript method binding When the button is clicked, the XPage is submitted and the JavaScript executes The output from the print statement can be seen in the trace file Listing 5.8 JavaScript Method Binding Expression How Does XPages Extend JSF? 153 Client ID Binding Expressions An ID binding expression is delimited using #{id: and } The ID of the user component whose client ID you want to compute is specified in the content of the computed expression, as shown in Listing 5.9 ID expressions are typically used as part of a multipart expression Listing 5.9 Client ID Binding Expression Multipart Binding Expressions A multipart expression allows static and dynamic content to be mixed In Listing 5.10, the value of the Computed Field combines static text, a client ID computed expression, and a JavaScript computed expression Listing 5.10 Multipart Value Binding Expression Simple Actions A simple action is a special type of method binding which is represented by a tag in the XPage and its behavior can be configured using properties Listing 5.11 shows how to configure a simple ExecuteScript action, which, in turn, invokes a JavaScript method binding Listing 5.11 Simple Action Method Binding Expression 154 Chapter XPages and JavaServer Faces XPages Default Variables Earlier in this chapter, the default JSF variables were listed (see Table 5.1) XPages provides some additional default variables for the Domino application developer Figure 5.4 shows an XPage that contains a table listing all the default variables, their value, and a short description of each variable Refer to the XPage named DefaultVariables in chapter5.nsf to see how this table was generated At the end of the list, the three new XPages default variables are listed: • viewScope: Map containing the view scope values • context: XspContext instance for the current request • database: Database instance for the current request • session: Session instance for the current request • sessionAsSigner: Session instance with the credentials of the XPage signer • sessionAsSignerWithFullAccess: Session instance with the credentials based on those of the XPager signer and with fill administrative access Figure 5.4 Table of default variables Chapter 6, “Building XPages Business Logic,” covers XPages default variables and examples of their usage in more detail A short description of each of the XPages default variables is provided next How Does XPages Extend JSF? 155 viewScope XPages introduces this new scoped variable to supplement the default scoped variables: requestScope, sessionScope, and applicationScope The viewScope variable allows you to scope your own variables to the lifetime of the associated view, such as XPage As previously mentioned, the state of a view can be cached between requests so that multiple requests act on the same state of the XPage The view is restored at the beginning and saved at the end of each request and any view scope variables are saved and restored as part of this process The viewScope object is a map, so you can add your own variables keyed by name By default, this map is empty, so you can select whatever names you want without concern for name clashes The variables you add must be serializable for their state to be saved context The context variable provides access to the XPages XSPContext object, which is an instance of com.ibm.xsp.designer.context.XSPContext The context object provides XPagesspecific contextual information about the current request, such as access to the associated user, timezone, locale, and so on It also provides numerous utility methods that can be used within your application logic, such as page navigation, HTML filtering, and so on database The database variable provides access to the Database object, which is an instance of lotus.domino.Database The database object provides access to the current Domino database and supports a wide range of database centric operations The complete documentation for the Database class is available in the Java/CORBA Classes section of the Lotus Domino Designer Basic User Guide and Reference help document, which is part of the Domino Designer help Use Help > Help Contents to access this documentation session The session variable provides access to the Session object, which is an instance of lotus.domino.Session The session is assigned credentials based on those of the current user The session is restricted by the application’s ACL and the security tab of the server’s Domino Directory entry The complete documentation for the Session class is available in the Java/CORBA Classes section of the Lotus Domino Designer Basic User Guide and Reference help document sessionAsSigner The session variable provides access to the Session object, which is an instance of lotus.domino.Session The session is assigned credentials based on those of the signer of the XPages’ design element The session is restricted by the application’s ACL and the Security tab of the server’s Domino Directory entry The complete documentation for the Session class is available in the Java/CORBA Classes section of the Lotus Domino Designer Basic User Guide and Reference help document 156 Chapter XPages and JavaServer Faces sessionAsSignerWithFullAccess The session variable provides access to the Session object, which is an instance of lotus.domino.Session The session is assigned credentials based on those of the signer of the XPages’ design element and allows full administrative access to the application’s data The signer must have permission for full administrative access or this session is not created and will not be available The complete documentation for the Session class is available in the Java/CORBA Classes section of the Lotus Domino Designer Basic User Guide and Reference help document Conclusion This concludes the overview of how XPages is built on top of JSF You learned how XPages extends JSF to add new capabilities and enhanced behaviors while maintaining the JSF standard As previously mentioned, XPages is currently built with JSF version 1.1, so if you plan to read more about JSF, this is the version to reference C H A P T E R Building XPages Business Logic This is the first of two chapters where you learn about adding business logic to your XPages application This chapter introduces the fundamental principles: how to add your business logic, simple actions, and using JavaScript with XPages This chapter explores the differences between creating server and client-side business logic and explains the Script Editor tool You also learn about some of the common objects that you can use from within your business logic Be sure to download the chapter6.nsf file provided online for this book to run through the exercises throughout this chapter You can access these files at www.ibmpressbooks.com/title/ 9780132486316 Signing the Sample Applications In this and the subsequent chapter, you preview samples that contain business logic, so it is recommended that you sign the sample database to avoid receiving execution control list (ECL) alerts You can assign each database from Designer by right-clicking it in the application navigator and selecting Application > Sign Design Adding Business Logic Your business logic is normally executed in response to a user action, such as when a user clicks a button to submit a page, you might want to process the data that has been inputted To achieve this, when editing an XPage in Designer, use the Events tab to add business logic to the onclick event for the respective button There are two main options for adding your business logic: Server or Client Service logic executes in the XPages engine and has access to the XSP representation of the page and the associated XSP runtime artifacts Client logic is running in a browser context and has access to the browser Document Object Model (DOM) and some additional artifacts when running in the Notes client (more on this in Chapter 13, “XPages in the 157 158 Chapter Building XPages Business Logic Notes Client”) Figure 6.1 shows the Events tab with the Server subtab selected This is your starting point for adding business logic that executes on the server When Server is selected, you see a Server Options section available This is only available when adding server-side business logic, and these options are discussed in Chapter 11, “Advanced Scripting.” Simple Actions Events Tab Server Logic Figure 6.1 Server Options Events tab with Server and Simple Actions selected Within both the Client and Server subtabs, there are options to use Simple Actions or the Script Editor A simple action represents some standard business logic, such as creating a response document, that can be configured by simply just changing its properties The intent is to free the application developer from having to write (and debug) code for common actions Figure 6.2 shows the Events tab with the Client subtab selected and the Script Editor option selected This allows you to view the client-side JavaScript expression, which executes when the specified event occurs You can also open the Script Editor dialog from here, which provides additional features to help you add scripting logic Adding Business Logic 159 Client Logic Events Tab Figure 6.2 Script Editor JavaScript Editor Events tab with Client and Script Editor selected So, what happens in your XPage when you use one of these options to add some business logic? There are four possible options: • Server simple action • Server script • Client simple action • Client script The good news is that in the XPages markup there is a single syntax that can be used for all four options, so there is only one thing you need to learn: the xp:eventHandler tag The xp:eventHandler tag is a component that associates business logic with any control in an XPage You have seen this pattern before (xp:dataTimeHelper) where XPages uses a child tag to add new behavior to its parent So, the xp:eventHandler tag can be nested inside any control tag when you want to trigger business logic in response to an event fired from the control, and that business logic can be server and/or client-side simple actions and/or JavaScript Yes, you can combine client-side and server-side business logic in response to the same event! An example of this is where you might want to prompt the user for confirmation 160 Chapter Building XPages Business Logic before deleting documents on the server The client-side logic executes first, and then the server-side logic executes unless the client-side logic prevented submission of the page Using the xp:eventHandler Tag Listing 6.1 shows a snippet of XPages markup that includes some logic to create a new Date object that contains the current date and time, followed by a Computed Field that displays this value A converter ensures that the value is presented correctly for the end user’s locale Listing 6.1 XPages Sample to Display the Current Date/Time This view scope value is created as the page is being loaded, using the beforePageLoad event, and can subsequently be updated using server or client-side simple actions or JavaScript Refreshing Using a Server-Side Simple Action Use the following steps to add logic that allows the value in the Computed Field to be updated using a server-side simple action (the completed sample is available in XPage named CurrentTime): Add a button to the XPage Go to the Event tab and select Server and Simple Actions (this should be the default) Select Add Action, and then select the Set Value simple action Set Binding to be a computed value, select Expression Language, and enter viewScope.now Set Value to be a computed value, select JavaScript (Server Side) and enter new Date() Adding Business Logic 161 Save the XPage Listing 6.2 shows the markup that is generated for you An xp:eventHandler tag is added as a child of the button control and is configured as follows: The event property is set to onclick, which means the event handler is triggered in response to the user clicking the button The submit property is to true, which causes the page to be submitted The refreshMode is set to complete, which means the entire page will be redrawn The action property is set to the xp:setValue tag, which represents the single action to be invoked Listing 6.2 Server Simple Action to Update the Current Date/Time The xp:eventHandler causes the runtime to add some client-side JavaScript to the rendered page This JavaScript adds a listener to the button, which responds to the onclick event by submitting the page This is the line of code in the rendered page, which causes this to happen: XSP.attachEvent(“view:_id1:_id3”, “view:_id1:button1”, “onclick”, null, true, false); If you preview this page, you can click this button and see the page being submitted and the current date/time being refreshed when the page is redisplayed If you a view source on the previewed page, you can see the preceding script in the generated markup Refreshing Using Server-Side JavaScript Refreshing using server-side JavaScript is similar to the previous simple action example except, in this case, the supplied JavaScript expression is executed Here are the steps: 162 Chapter Building XPages Business Logic Add a button to the XPage Go to the Event tab and select Server and Script Editor Enter the expression viewScope.put(“now”, new Date()) Save the XPage Listing 6.3 shows the markup that is generated for you The only difference in how the xp:eventHandler tag is configured is that now the action property contains a computed expression that contains the JavaScript to be executed Listing 6.3 Server JavaScript to Update the Current Date/Time Refreshing Using a Client-Side Simple Action The steps to add a client-side simple action are similar to the ones you used earlier to add a server-side simple action As you would expect, the available simple actions differ between client and server because the environment where the simple actions execute is different, more on this later in the section, “Simple Actions.” Follow these steps: Add a button to the XPage Go to the Event tab and select Client and Simple Actions Select Add Action and select the Execute Client Script simple action Set Language to be a JavaScript (Client Side) Set Condition to be the following JavaScript expression: var computedField1 = document.getElementById(“#{id:computedField1}”); computedField1.innerHTML = new Date(); Save the XPage This time, the xp:eventHandler tag has the script property set The script property is used when a client-side simple action or JavaScript is to be executed The script in this sample gets the DOM element corresponding to computedField1 using the getElementById method and then updates the contents of the element by setting the innerHTML property to the current Adding Business Logic 163 time As you saw earlier, the action property is used for server-side simple actions and JavaScript An xp:executeClientScript tag is set as the value for the script property This represents the client-side simple action An xp:executeClientScript tag has its own script property, which is set to the client-side JavaScript to be executed In the generated markup, notice that the submit property is set to true If you preview the page and click this button, you see that the current date/time changes momentarily and then changes back to the previous value This is because the page is being submitted in response to the button click and then redrawn with the only server value To prevent the submit from happening, you need to make sure the submit property on the xp:eventHandler is set to false Now, if you preview the page, notice that the date/time value does change and the page is no longer submitted Also, notice that the format of the date/time string is different This is because a pure client-side operation has been executed and the value is not being set in the view scope and converted for display using the configured converter The client-side script is just updating the HTML within the browser or Notes client Listing 6.4 shows the XSP markup for this example Listing 6.4 Client Simple Action to Update the Current Date/Time Listing 6.5 shows the client-side script that the xp:executeClientScript caused to be included in the rendered page The xp:eventHandler also includes client-side script that causes this method to be invoked when the associated button is clicked Listing 6.5 JavaScript Rendered by xp:executeClientScript function view id1 id7_clientSide_onclick(thisEvent) { var computedField1 = document.getElementById(“view:_id1:computedField1”); computedField1.innerHTML = new Date(); } 164 Chapter Building XPages Business Logic Refreshing Using Client-Side JavaScript Refreshing using client-side JavaScript uses the same script as the previous example Here are the steps: Add a button to the XPage Go to the Event tab and select Client and Script Editor Enter the following expression: var computedField1 = document.getElementById(“#{id:computedField1}”); computedField1.innerHTML = new Date(); Save the XPage Listing 6.6 shows the markup that is generated for you You can see that now the script expression is associated with the script property on the xp:eventHandler tag and, this time, the submit property is set to false, so no manual update of the XPage is required Listing 6.6 Client JavaScript to Update the Current Date/Time As you expect, the rendered JavaScript is almost identical to the previous case where the xp:executeClientScript was used and the behavior when clicking the button is the same Event Handler Properties This section describes the properties associated with the xp:eventHandler tag Numerous properties are relevant when using the event handler to make an AJAX request, such as for a partial refresh of the page These properties are described in Chapter 11 and elsewhere • event: Name of the event, which triggers the associated server action or client script • execId: ID of the control, which is the root of the branch used for the partial execution of the JSF lifecycle • execMode: Execution mode for the event handler Valid values are • complete: Lifecycle is executed on the complete control hierarchy (default) • partial: Lifecycle is executed on the part of the branch of the control hierarchy specified by the execId Adding Business Logic NOTE 165 Chapter 11 covers the uses of the execMode property in detail • handlers: Collection of client event handlers Each handler has the following properties: • type: Currently only text/javascript is supported • script: The client script that is executed • renderkit: Use HTML_BASIC if this script is for the web only and HTML_RCP if this script is for the Notes client Listing 6.7 shows how to have different client scripts for the browser and Notes clients Other examples of web and Notes platform differentiation are covered in Chapter 13 Listing 6.7 Renderkit-Specific Client Script Handlers • loaded: A boolean flag that indicates if the event handler should be included in the control hierarchy when the page is loaded Set this to false if you want the event handler to be omitted when the page is loaded The default value is true, and one example where you would use this is if there was business logic didn’t apply to a particular user based on their application roles 166 Chapter Building XPages Business Logic • navigate: A boolean flag that indicates if navigation should be performed when the event associated with the event handler is being processed • refreshId: ID of the control, which is the root of the branch to be refreshed when partial refresh has been specified • refreshMode: The refresh mode for the event handler Valid values are • complete: Entire page is refreshed (default) • partial: Part of the page specified by the refreshId is refreshed • norefresh: No part of the page is refreshed • rendered: Boolean flag that indicates in the event handler should be rendered as part of the page Set this to false if you want the event handler to be omitted when the page is rendered • save: Boolean flag that indicates if a save operation should be performed when the event handler is processed Set to true to automatically save the data sources on the page • submit: Boolean flag that indicates if the page should be submitted when the event associated with this event handler is triggered Set to true to submit the page • parameters: Collection of parameters and name/value pairs, which are made available when the action associated with the event handler is executed • action: The server action that executes when this event handler is triggered This can be a simple action, a JavaScript expression or a Java method • immediate: Boolean flag that indicates that processing of the server action associated with the event handler should proceed after the apply-request-values phase of the JSF lifecycle and before the inputted values are validated If the action causes a navigation to another XPage or causes the page to be redrawn, the remaining phases of the lifecycle are not executed The immediate property is set to true when you specify a button type is Cancel (as shown in Listing 6.8) because this allows the operation to proceed even if the inputted values are not valid Because the update-model phase has not executed when the action is processed, the latest values are not available in the model If the update-model phase doesn’t execute (which is the norm with immediate set to true), the values entered by the user are discarded If, during the processing of an immediate action, the inputted values need to be referenced, one option is to reference them directly from the control Be aware that, if you this, the values are available in string format only; they have not been converted to the correct type or validated Simple Actions Listing 6.8 167 Using the immediate Property for a Cancel Button Using Immediate with an Input Control The immediate property is also supported for input controls When set to true, the inputted value is validated during the apply-request-values phase of the JSF lifecycle If validation fails on a control marked as immediate, the response is rendered and the validation errors are available in the response Non-immediate controls may not be validated if a validation error in an immediate control caused the response to be rendered Non-immediate controls only validate in the process-validations phase of the lifecycle • onComplete: Used when the event handler triggers an AJAX request This property is the client script to be executed after the AJAX request is executed • onError: Used when the event handler will trigger an AJAX request This property is the client script to be executed if there is an error executing the AJAX request • onStart: Used when the event handler will trigger an AJAX request This property is the client script to be executed before the AJAX request is executed • script: The client script to be executed when the associated event associated with the event handler is triggered Using onXXX Properties The onComplete, onError, and onStart properties can be accessed by selecting the event handler in the Outline view and using All Properties or by typing them directly into the XPage in source mode Simple Actions Previously, you saw how some examples of simple actions that execute in the client and on the server Simple actions are represented by tags in the XPage and provide reusable business logic that can be configured by setting the tag properties In this section, you learn how to use all the simple actions and you find descriptions of their properties Required properties are identified; if 168 Chapter Building XPages Business Logic you save an XPage without specifying a value for the required properties, the XPage has errors (which you can see in the Problems panel) Localizable properties are also identified; these properties can be localized using the built-in localization features, which you learn about in Chapter 15, “Internationalization.” The following sections describe each of the simple actions, its properties, and sample usage Change Document Mode The change document mode simple action changes the access mode, read-only or editable, for the specified document Tag: xp:changeDocumentMode Properties: • var: The variable name of the document whose mode is to be changed If not specified, this defaults to currentDocument (the closest available Domino Document) • mode: The access mode to set for the document This is a required property The mode can be set to one of the following values: • toggle: Changes the document mode to edit mode so its contents can be modified • readOnly: Changes the document mode to read only; editing is not possible • autoEdit: Changes the document mode to edit if the current user has permission to edit the document; otherwise, set mode to read only • toggle: Toggles the document mode between read-only and edit mode (for example, if document is currently read-only, toggle to edit mode and vice versa) Sample: Listing 6.9 shows the change document mode simple action being used to set the mode of the Domino document referenced by dominoDocument1 to editable Note that the button that triggers the simple action is displayed only when the document is not already editable TIP If you were to test the sample shown in Listing 6.9 using Preview in Browser with the normal Anonymous as Author access, you find it doesn’t work When you click the button, the document stays in edit mode This is because you need to change Anonymous access to Editor to allow users to edit a document This can trip you up during development, but it’s reassuring to know that users with the incorrect access level cannot edit existing documents, even if the application puts them in a position to so Simple Actions Listing 6.9 169 Change Document Mode to Editable Confirm Action The confirm simple action presents the user with a message and options to allow execution to continue or stop Tag: xp:confirm Properties: • message: The message displayed to the user This is a required property Sample: Listing 6.10 uses three simple actions, namely the action group, delete document, and confirm actions The action group and delete document actions are covered later in this section The confirm action causes a JavaScript function to be included in the rendered page This function is called after the Delete button is clicked, but before the page is submitted, and prompts the user with the specified message and provides her the opportunity to either proceed or cancel TIP You need to ensure that Anonymous access is allowed to delete documents before this sample works Listing 6.10 Confirm Before Deleting a Document Create Response Document The create response document simple action creates a response document and opens the specified page to edit it Tag: xp:createResponse Properties: • name: The name of the XPage to open to create the response This is a required property • parentId: The document ID of the parent document for the new response This is a required property Sample: Listing 6.11 shows the create response simple action being used to create a response with the current document as its parent and the CarDetails.xsp page being used to edit the new response Listing 6.11 Create Response Document Simple Actions 171 Delete Document The delete document simple action, as the name implies, deletes a document and then opens the specified page By default, the current document will be deleted Tag: xp:deleteDocument Properties: • message: An optional message displayed to the user before the specified document is deleted This is a localizable property • var: The variable name that references the document to be deleted, if not specified this defaults to currentDocument (closest available Domino Document) • name: The name or symbolic identifier of the XPage to be opened after the specified document has been deleted This is a required property The name can be set to the name of an XPage or one of the following symbolic identifiers: • $$PreviousPage: The previously opened page • $$HomePage: The launch page, as specified in the application properties Sample: Listing 6.12 shows the delete document being used to delete the document, including allowing the user to confirm that the document should be deleted If the document is deleted, navigation proceeds to the previous page The Delete button is not displayed if the current document is new and has not yet been saved because there is nothing to delete in this case Listing 6.12 Delete the Current Document and Navigate to the Previous Page 172 Chapter Building XPages Business Logic Delete Selected Documents The delete selected documents simple action deletes the documents selected in a view after first prompting the user to confirm this action Tag: xp:deleteSelectedDocuments Properties: • message: A message displayed to the user before the specified documents are deleted This is a localizable property • noFilesSelectedMessage: A message that will be displayed if no documents are selected in the specified view This is a localizable property • view: The variable name of the view from which the selected documents will be deleted This is a required property Sample: Listing 6.13 shows a sample action that deletes documents from a view and the message that is displayed to the user before the documents are deleted and the message to use if no documents are selected TIP For this simple action, the convention is to use the column display properties to display a checkbox in the first column of the specified view when you want users to be able to delete selected documents from that view Listing 6.13 Delete the Documents Selected in a View Simple Actions 173 Execute Client Script The execute client script simple action executes a client-side JavaScript This is a client simple action Tag: xp:executeClientScript Properties: • script: The client script to be executed This is a required property Sample: Listing 6.14 shows the execute client script simple action being used to display an alert message to the end user Note that the event handler tag is configured with submit set to false so that clicking the button does not cause the page to be submitted Listing 6.14 Executing a Client Script Execute Script The execute script simple action executes a server-side JavaScript expression Tag: xp:executeScript Properties: • script: The server script to be executed This is a required property Sample: Listing 6.15 shows the execute script simple action being used to display a message in the log file 174 Chapter Listing 6.15 Building XPages Business Logic Executing a Server Script Modify Field The modify field simple action modifies a field in the specified document or the current document if none is specified Tag: xp:modifyField Properties: • var: The variable name that references the document to be modified, if not specified this defaults to currentDocument (closest available Domino Document) • name: The name of the field to be modified This is a required property • value: The new value to be set in the specified field This property is required and localizable Sample: Listing 6.16 shows how to use the modify field action to set a value in the current document after the page has loaded Listing 6.16 Modify Field Being Invoked After Page Has Loaded Simple Actions 175 the car description here>]]> Open Page The open page simple action navigates to a specific page; you can set the document ID of an existing document that can be opened for reading/editing or you can cause the creation of a new document Tag: xp:openPage Properties: • var: The variable name that references a document whose ID is passed to the page about to be opened This value is used if no document ID has been specified using the documentId parameter • documentId: A document ID that is passed to the page about to be opened • parameters: A collection of user defined parameters, name/value pairs, which is passed to the page that is about to be opened • name: The name of the page to be opened This is a required property • target: The new value to be set in the specified field The target property can be set to one of the following values: • openDocument: Used to when you want to open a page to read a document • editDocument: Used to when you want to open a page to edit a document • newDocument: Used to when you want to open a page to create a new document Sample: Listing 6.17 shows how to use the open page action to open a specific document for editing Listing 6.17 Open Page Being Used to Open a Document for Editing 176 Chapter Building XPages Business Logic Publish Component Property The publish component property simple action publishes the value for a component event This is a client simple action Tag: xp:publishValue Properties: • name: The name of the property to be published This is a required property • value: The value of the property to be published This is a required property • type: The type of the value being published The default value is text The type property can be set to one of the following values: • string: Used to when the component value is a string • boolean: Used to when the component value is a boolean • number: Used to when the component value is a number • json: Used to when the component value is a JavaScript Object Notation (JSON) object JSON is covered in more detail in Chapter 11 Sample: Listing 6.18 shows how to use the publish component property action to publish a value from a column value Simple Actions Listing 6.18 177 Publishing a Column Value as a Component Property [...]... features of the standard XPages UI themes, and explains how to create your own customized themes xxviii Mastering XPages • Chapter 15, “Internationalization”: Read this chapter to learn how your XPages applications can be translated so that they look, feel, and behave as native applications in any geographical locale Part VI, “Performance, Scalability, and Security”: Up to this point this book has... appreciation of what’s happening under the XPages hood This is an essential prerequisite to some of the more advanced topics, like XPages performance and scalability • Chapter 4, “Anatomy of an XPage”: This chapter examines the XSP markup language and gives a simple example of all the standard elements (controls and such) that can be used in an XPage It provides a great broad-based view of XPages basics... Stansel and Ellice Uffer Finally, a great big THANK YOU, as always, to our customers and business partners, particularly the early adopters who got behind XPages at the get-go and made it the success that it is today! About the Authors The authors of this book have a number of things in common All three hail from Ireland, work for the IBM Ireland software lab, and have made significant contributions to the. .. encouragement and advice along the way We are indebted to Maire Kehoe who always parachutes in for us to solve thorny problems at the drop of a hat—where would we be without you! Padraic Edwards and Teresa Monahan deserve our kudos for helping out on composite application use cases, and to Teresa again for her CK Editor brain dump And because all the authors are based in Ireland, you can well imagine that... all about application look and feel You learn not just how to make your apps look good and behave well, but how to do so for an international audience! • Chapter 14, XPages Theming”: This chapter teaches you how to manage the appearance and behavior of your application s user interface It provides an in-depth look at ad-hoc XPages application styling using cascading style sheets, as well as the main... an existing application to a Web 2.0 level XPages is a Java runtime environment that supports all the defining features of Web 2.0, and it extends a standards-based framework known as JavaServer Faces (JSF) This JSF standard is commonly used as a base technology across many other commercial web -application development offerings, such as IBM Rational Application Developer, Oracle JDeveloper, JBoss, and. .. understated This book’s goal is to fill that gap and provide a single comprehensive guide that enables readers to confidently take on, or actively participate in, a realworld XPages application- development project Preface xxv Approach This book’s objective is to impart as much practical XPages knowledge as possible in a way that is easy for the reader to digest The authors seek to cover all aspects of the. .. have mastered XPages fundamentals • Chapter 13, XPages in the Notes Client”: XPages in the Notes client initially explains how you can take your XPages web applications offline and then goes on to highlight how you can take advantage of powerful features of the client platform itself, and how to manage applications that run in both environments Part V, Application User Experience”: This part is all... concentrated on the skills and tools you need to know to develop state-of -the- art collaborative applications Part VI shifts to deployment and what you need to do to make sure your applications meet customer expectations in terms of performance, scalability, and security • Chapter 16, Application Performance and Scalability”: This chapter highlights various tips and tricks that will enable you to tune... describe all the details of the XSP tags, Java and JavaScript classes It provides examples of how to use these resources to find the information you need • Appendix B, XSP Style Class Reference”: This appendix identifies all the standard XPages CSS files and style classes used to build XPages application user interfaces It’s an essential quick reference for Chapter 14 • Appendix C, “Useful XPages Sites on the

Ngày đăng: 25/08/2016, 22:03

Từ khóa liên quan

Mục lục

  • Contents

  • Foreword

  • Preface

  • Part I: Getting Started with XPages

    • Chapter 1 An Introduction to XPages

      • XPages Fundamentals

      • Brand New Technology?

      • A Different Development Paradigm

      • The More Things Change, the More Things Stay the Same

      • New Horizons

      • Conclusion

      • Chapter 2 Getting Everything You Need

        • Downloads, Versions, and Locations

        • Installing Domino Designer

        • Installing Client Fix Packs

        • Client Configuration

        • Quick Tour of Domino Designer

        • Conclusion

        • Chapter 3 Building Your First XPages Application

          • Laying the Foundations

          • Forms and Views

          • Building an XPages View

          • Completing the CRUD

          • Conclusion

Tài liệu cùng người dùng

Tài liệu liên quan