1.6 Getting started with Liferay Portal 18 Installing Liferay Portal 6.x 18 ■ Registering users with Liferay Portal 20 ■ Creating a public portal page in Liferay Portal 21 ■ Adding port
Trang 1Ashish Sarin
Covers Portlet 2.0, Spring 3.0 Portlet MVC, WSRP 2.0, Portlet Bridges, Ajax, Comet, Liferay, GateIn, Spring JDBC and Hibernate
IN ACTION
Trang 2BEST PRACTICESINSIDETHEBOOK
Use user attributes to obtain user
Handle portal server–specific
Choose appropriate portlet
Add custom JavaScript and CSS files
to a portal page using MARKUP_HEAD element 108 3.3.5Choose appropriate PortletSession
Evaluate use of container-runtime options 123 3.7.1Use actionScopedRequestAttributes
Choose wisely when to use
servletDefaultSessionScope
Consider performance impact of
Choose appropriate validation token
Use Apache Commons FileUpload for
Override portlet request and response
objects’ functionality using wrapper classes 158 4.6.2
Simplify portlet URL creation using
(Continued on inside back cover)
Trang 3Portlets in Action
Trang 5Portlets in Action
ASHISH SARIN
M A N N I N G
SHELTER ISLAND
Trang 6For online information and ordering of this and other Manning books, please visit
www.manning.com The publisher offers discounts on this book when ordered in quantity For more information, please contact
Special Sales Department
Manning Publications Co
20 Baldwin Road
PO Box 261
Shelter Island, NY 11964
Email: orders@manning.com
©2012 by Manning Publications Co All rights reserved
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps
Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end Recognizing also our responsibility to conserve the resources of our planet, Manning booksare printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine
Manning Publications Co Development editors: Emily Macel, Jeff Bleiel
20 Baldwin Road Copyeditor: Andy Carroll
PO Box 261 Proofreader: Katie Tennant
Shelter Island, NY 11964 Typesetter: Dennis Dalinnik
Cover designer: Marija Tudor
ISBN: 9781935182542
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – MAL – 17 16 15 14 13 12 11
Trang 7brief contents
P ART 1 G ETTING STARTED WITH PORTLET DEVELOPMENT 1
1 ■ Introducing portals and portlets 3
2 ■ The portlet lifecycle 48
3 ■ Portlet 2.0 API—portlet objects and container-runtime options 86
4 ■ Portlet 2.0 API—caching, security, and localization 132
5 ■ Building your own portal 167
6 ■ Using the portlet tag library 207
P ART 2 D EVELOPING PORTLETS USING S PRING
AND H IBERNATE 231
7 ■ Getting started with Spring Portlet MVC 233
8 ■ Annotation-driven development with Spring 281
9 ■ Integrating portlets with databases 334
Trang 9contentspreface xix
acknowledgments xxi about this book xxii about the cover illustration xxvii
1 Introducing portals and portlets 3
1.1 What is a portal? 4 1.2 Benefits of web portals 6
Enriched user experience 6 ■ Unified information view 9
1.3 What is a portlet? 10 1.4 Why use portlets? 12
Inter-portlet communication vs inter-servlet communication 12 ■ Portlets vs widgets 13 Creating mashups 15
1.5 Portal infrastructure 15
The portlet container 15 ■ The portal server 16
Trang 101.6 Getting started with Liferay Portal 18
Installing Liferay Portal 6.x 18 ■ Registering users with Liferay Portal 20 ■ Creating a public portal page
in Liferay Portal 21 ■ Adding portlets to a Liferay Portal page 23 ■ Roles and permissions in Liferay Portal 24
1.7 Setting up the development environment 26
Configuring Eclipse IDE 26 ■ Setting up the project structure 34
1.8 The Hello World portlet example 35
Creating a Hello World portlet 35 ■ Building the Hello World project with Ant 39 ■ Building the Hello World project with Maven 42 ■ Adding the Hello World portlet to
a portal page 43 ■ Undeploying a portlet application 46
1.9 Summary 46
2 The portlet lifecycle 48
2.1 Requirements for the User Registration portlet 49 2.2 Portlets vs servlets—an in-depth look 51
Portlet and servlet containers 51 ■ Portlets—web components with multiple request-processing phases 52
2.5 Generating portlet content based on portlet mode 62
Writing content generation methods for each portlet mode 64 Defining support for portlet modes 67
2.6 Portlet development in depth 68
The Portlet API objects 69 ■ Creating JSPs to display portlet content 70 ■ The portlet deployment descriptor 72 Dispatching portlet requests using the PortletRequestDispatcher 73 Internationalization and localization using resource bundles 75 Portlet initialization parameters 76 ■ Creating portlet URLs 76 Container-runtime options 78
Trang 112.7 Implementing the User Registration portlet 80
The UserRegistrationPortlet class 81 ■ JSP pages 84
2.8 Summary 85
3 Portlet 2.0 API—portlet objects and
container-runtime options 86
3.1 Requirements for the Book Catalog portlet 87
3.2 Portlet request objects 92
Portlet request objects and lifecycle interfaces 92 ■ PortletRequest constants 94 ■ PortletRequest methods 97 ■ Handling portal server–specific requests using PortalContext 99
3.3 Portlet response objects 100
Encoding URLs with the encodeURL method 102 ■ Generating content using RenderResponse 103 ■ Responding to an action using ActionResponse 104 ■ Choosing an appropriate phase for an action 107 ■ Adding custom JavaScript and CSS files to a portal page 108
3.4 Storing user-specific data in a portlet session 112
PortletSession object and methods 112 ■ PortletSession usage
in the Book Catalog portlet 113 ■ Obtaining session attributes using PortletSessionUtil 114 ■ An in-depth look at portlet session scopes 116 ■ Portlet session and content caching 118 Similarities between HttpSession and PortletSession 118 Sharing session data across portlet applications 119
3.5 Discovering the portlet environment using
PortletContext 119 3.6 Retrieving portlet configuration using PortletConfig 120 3.7 Container-runtime options 121
Using actionScopedRequestAttributes 123 ■ Using servletDefaultSessionScope 127 ■ Using escapeXml 128 Using renderHeaders 130 ■ Specifying Portlet and Portlet application container-runtime options 130
3.8 Summary 131
Trang 124 Portlet 2.0 API—caching, security, and localization 132
4.1 Caching generated content 133
Expiration-based content caching 134 ■ Validation-based content caching 137
4.2 Localizing portlet content 141
Implementing portlets to support localization 142 Changing locales using built-in portlets 143
4.3 Portlet modes in depth 143
Custom portlet modes 144 ■ Portal-managed and portlet-managed portlet modes 148 ■ Portlet modes and markup types 150
4.4 Portlet window states in depth 151
Custom window states 152 ■ Portlet window states and markup types 153
4.5 Programmatic security 154 4.6 Uploading files, wrapping requests and responses, and
creating portlet URL generation listeners 156
Uploading files 156 ■ Using wrapper classes 158 Using the PortletURLGenerationListener interface 159
4.7 Designing portable portlets 161
Portal server features and limitations 162 Designing for change 163
4.8 Summary 166
5 Building your own portal 167
5.1 Requirements for Book Portal 168 5.2 Getting started developing Book Portal 170
Creating an organization for Book Portal 171 Creating roles for Book Portal users 173 ■ Mapping roles
to the Book Portal organization 174 ■ Creating Book Portal users and assigning them to the organization 175 Mapping users to roles 177
Trang 135.3 Creating portal pages and adding portlets 178
Creating a Home portal page 178 ■ Adding an Announcements portlet 182 ■ Adding an RSS feed portlet 184 Setting permissions for portal pages and portlets 185
Using the built-in Document Library and Book Catalog portlets together 188 ■ Setting permissions for displaying the book catalog 191 ■ Setting permissions for displaying discussion forums 192
5.4 Configuring Liferay Portal server settings 193
Setting the authentication mechanism 194 ■ Specifying the default user associations 195
5.5 Developing with the Liferay Plugins SDK 196
Configuring the Plugins SDK 197 ■ Developing portal themes 198 ■ Developing page layout templates 203
5.6 Summary 206
6 Using the portlet tag library 207
6.1 Using the tag library to build a Book Catalog portlet 208 6.2 Accessing portlet-specific objects using
Using the <actionURL> tag 213 ■ Using the
<renderURL> tag 220 ■ Using the <resourceURL> tag 220
6.4 Adding parameters to portlet URLs using <param> 221
Using the <param> tag 221 ■ Adding parameters using string concatenation 223
6.5 Creating portlet-specific HTML elements using
Trang 147 Getting started with Spring Portlet MVC 233
7.1 Why use Spring Portlet MVC? 234 7.2 Dependency injection and the application context 235
An e-commerce example 235 ■ Dependency injection and application contexts 237 ■ Web application contexts 240
7.3 A Hello World portlet, the Spring way 241
The Hello World portlet’s controller class 242 ■ The Hello World portlet’s JSP page 243 ■ The Hello World portlet’s portlet deployment descriptor 243 ■ The Hello World portlet’s web application context 244 ■ The Hello World portlet’s web application deployment descriptor 245
7.4 How Spring Portlet MVC works 246 7.5 Using DispatcherPortlet 248
7.6 Using the web application context 249
Naming web application context XML files 249 ■ Scope of beans defined in the web application context XML 250
7.7 Using built-in controllers 252
Using the Controller interface 253 Using the AbstractController 254 Using the ParameterizableViewController 256 Using the PortletModeNameViewController 257 Using the PortletWrappingController 259
7.8 Using built-in handler mappings 260
Developing a Book Catalog portlet with Spring Portlet MVC 262 Using PortletModeHandlerMapping 263
Using ParameterHandlerMapping 264 Using PortletModeParameterHandlerMapping 267 Using AbstractHandlerMapping 270
7.9 Using handler interceptors 272
Implementing and configuring a handler interceptor 272 Processing requests using handler interceptors 273
Trang 157.10 Handling exceptions 276
Request handling with exceptions 277 ■ Mapping exceptions
to a view based on the exception class 278
Identifying controllers with @Controller 285 ■ Classpath scanning and autoregistration 286 ■ Dependency injection using @Autowired and @Qualifier 288 ■ Dependency injection using @Resource and @Inject 289 ■ Mapping requests to handlers and methods using @RequestMapping 290 ■ Identifying render methods with @RenderMapping 295 ■ Identifying action methods with @ActionMapping 297 ■ Passing request parameters using @RequestParam 299 ■ Identifying model attributes using @ModelAttribute 301 ■ Reusing model attributes using
@SessionAttributes 304 ■ Handling exceptions with
@ExceptionHandler 307 ■ Initializing WebDataBinder using @InitBinder 307
8.4 Configuring beans that provide annotation support 310 8.5 Validating forms using Spring and JSR 303 313
The Spring Validation API 313 ■ Validating beans with JSR 303 316
8.6 Spring’s form tag library 323
8.7 Unit testing with mock objects and TestContext 324
Ant buildfile to run unit tests 325 ■ Unit testing with mock objects 326 ■ Unit testing with Spring’s
Trang 169 Integrating portlets with databases 334
9.1 Combining portlets and databases 335 9.2 Exploring the Book Catalog portlet’s database tables 336
The BOOK_TBL table 337 ■ The TOC_TBL table 337
9.3 Spring’s JDBC module for database interaction 338
Defining a data source 339 ■ Creating database connections 345 ■ Creating DAOs 346 ■ Creating service interface and implementation classes 349
9.4 Accessing Spring beans from non-Spring objects 351 9.5 AOP support in Spring Framework 352
Spring AOP and AspectJ annotations 354 ■ Using AspectJ annotations to create aspects 354
9.6 Transaction management support in Spring
Framework 358
Defining a transaction manager 358 ■ Specifying transactional methods 359 ■ Configuring annotation-driven transaction management 360
9.7 Using Hibernate for database interaction 361
Using the Java Persistence API (JPA) 362 ■ Mapping classes to relational database tables 363 ■ Connecting to a database 365 Using Spring with Hibernate 367
Adding support for EDIT portlet mode 379 ■ Writing a render method for EDIT portlet mode 380
10.4 Saving user preferences 382
Retrieving user preferences from the portlet request 382 Saving portlet preferences to the persistent store 383
Trang 1710.5 Saving preferences with PortletPreferences 384
Atomicity in saving preferences 386 ■ Concurrency issues in saving preferences 386 ■ Resetting preferences 386
10.6 Validating preferences 388
Validating preferences before setting them in PortletPreferences 389 ■ Validating preferences using PreferencesValidator 390 ■ Configuring Preferences Validator in the portlet deployment descriptor 392 Handling ValidatorException 395
10.7 Retrieving portlet preferences and personalizing
the portlet 397
Obtaining preferences in the portlet class and JSP pages 397 Personalizing content and behavior 400 ■ Defining portlet preferences in portlet.xml 403
10.8 Summary 404
11 Communicating with other portlets 405
11.1 Why do you need inter-portlet communication? 406
11.2 An inter-portlet communication example 407
11.3 Inter-portlet communication using portlet sessions 409
Defining multiple portlets in the portlet deployment descriptor 410 ■ Storing and retrieving information from PortletSession 411 ■ Inter-portlet communication
in action 415 ■ Advantages and disadvantages of using PortletSession 416
11.4 Inter-portlet communication using public
render parameters 417
Setting and retrieving public render parameters 418 ■ Methods related to public render parameters 423 ■ Advantages and disadvantages of using public render parameters 424 ■ Putting public render parameters to work 425
11.5 Inter-portlet communication using portlet events 425
Sending portlet events 427 ■ Receiving portlet events 432 Advantages and disadvantages of using portlet events 435 Event support in Spring Portlet MVC 436
11.6 Summary 436
Trang 1812.1 Ajax basics 439 12.2 Your first Ajax portlet 440
Creating a portlet that displays date and time 442 ■ Sending Ajax requests using the XMLHttpRequest object 442 ■ Handling Ajax requests using portlet or servlet components 444 ■ Retrieving the servlet response to update portlet content 445
12.3 Securing Ajax requests 447
Date/Time portlet’s security requirements and possible solutions 447 ■ Implementing security using portal server–specific APIs 448
12.4 Ajax support in Portlet 2.0 450
Serving resources using the ResourceServingPortlet interface 450 Sending a resource request using a resource URL 453
Serving resources the Spring Portlet MVC way 455
12.5 Downloading binary content using portlets 455 12.6 Resource URLs and caching 458
12.7 Creating a rich interface for the Book Catalog
portlet 459 12.8 Creating rich user interfaces using Ajax 461
Simplified Ajax with Dojo 462 ■ Simplified Ajax with jQuery 468 ■ Simplified Ajax with DWR 471
12.9 Creating real-time portlets using Polling and Comet 480
Polling—pulling data at regular intervals 481 Comet or Reverse Ajax—pushing data when it’s available 481 ■ Comet support in DWR 482 DWR integration with other frameworks 488
12.10 Cross-domain Ajax 488 12.11 Ajax and inter-portlet communication 489
Inter-portlet communication using Comet 490 ■ Inter-portlet communication using a JavaScript function 491
12.12 Summary 493
Trang 1913 Reusable logic with portlet filters 494
13.1 Types of portlet filters 495
13.2 Portlet filter interface methods and lifecycle 496
Portlet filter interface methods 496 ■ Portlet filter lifecycle 497
13.3 Using portlet filters with the Book Catalog portlet 499
13.4 Setting the portlet title with the portlet filter 500
13.5 Validating requests with portlet filters 503
13.6 Converting text to hyperlinks with portlet filters 505
14.4 Wicket portlets 525
Book Catalog Wicket web application requirements 525 Wicket web application project structure 526 ■ Developing the Book Catalog web application using Wicket 528 ■ Developing the Book Catalog portlet using a Wicket portlet bridge 530
14.5 Summary 532
15 Web Services for Remote Portlets (WSRP) 533
15.1 What makes remote portlets a reality? 535
15.2 Getting started with WSRP using Liferay Portal 538
15.3 Creating a WSRP producer and adding portlets to it 539
Trang 2015.4 Creating a WSRP consumer 545 15.5 Locally registering remote portlets 547 15.6 Registering WSRP consumers with WSRP producers 550
Out-of-band registration 551 ■ In-band registration 551 In-band and out-of-band registration
examples 551 ■ Leasing 553
15.7 Summary 554
Trang 21But even though Portlet 1.0 (JSR-168) had limitations, it didn’t stop businessesfrom taking advantage of the benefits web portals offered—personalization and con-tent aggregation The lack of support for some critical features in the Java Portlettechnology meant that portlets had to rely on portal server–specific extensions, whichresulted in portlets that were not portable across different portal servers and were notPortlet 1.0–compliant
In 2008, Portlet 2.0 (JSR-286) was released, and it addressed the limitations thatexisted in Portlet 1.0 Portlet 2.0 was a major step forward in the adoption of Java Port-let technology The portlet technology received a further boost when portlet bridgesmade it possible to develop applications using existing web frameworks like JSF,Wicket, Struts, and so on, without learning the Java Portlet technology
Towards the beginning of 2009, I started working on a portal project using let 2.0 Unlike the early days, I no longer had to worry about developing Ajax port-lets or implement ad hoc approaches to perform inter-portlet communication I felt
Trang 22that the Java Portlet technology had finally arrived It now addresses all the tures that were always expected of it
During this time, I also evaluated and used Spring Portlet MVC—a subframework
of Spring, specifically designed for developing Java portlets The use of Spring Portlet
MVC further simplified the development and testing of portlets, and it became myfavorite framework for developing portlets By early 2009, JSR-329 (Portlet 2.0 Bridgefor JavaServer Faces 1.2 specification) was started to simplify the development of JSF
portlets using Portlet 2.0; this further supported developing Java portlets using ing web frameworks
Developing portlets requires not only a good understanding of portlet technology,but also an understanding of how portlet technology can be used with other technolo-gies to develop real-world web portals, and that’s the topic of this book My goal was toopen up the exciting world of Java Portlet technology to you and help you get starteddeveloping portlets and web portals
Trang 23acknowledgments
Writing Portlets in Action has been a grueling task because of its length and the diverse
content it covers When I began writing in July 2009, I was not sure if I would be able
to consistently give the necessary time and energy to the project over a period of ayear or so
This book has largely been possible because of the readers who took time to postcomments on Manning’s Author Online forum The forum has been a constantsource of inspiration for me and has kept me motivated to complete the book I wouldlike to thank Bruce Phillips, Richard Palacios, Barbara Regan, John Joseph Ryan III,and Wayne Lund for taking the time to post their findings and suggestions in theforum, and also for participating in the technical reviews of the book Doug Warrendid an outstanding job of providing detailed comments on and improving the techni-cal content of the book Thanks also to the following reviewers who gave generously oftheir time: Joshua White, Lester Martin, Patrick Steger, Srini Penchikala, PrasadChodavarapu, and Jakub Holy
This book owes a great deal to Emily Macel at Manning for improving the tation and structure of the book and helping me transition from a developer to anauthor Special thanks to Jeff Bleiel for ensuring that the book met Manning’s stan-dards Thanks as well to Christina Rudloff for getting this book started and to pub-lisher Marjan Bace for giving me the opportunity to write for Manning Publications
Trang 24about this book
Portlets are web components, like servlets, that are responsible for accessing distinctapplications, systems, or data sources and generating markup fragments to presentthe content to web portal users The Java Portlet technology simplifies the process ofdeveloping web portals by providing personalization and content aggregation as anintegral part of the technology
Portlets in Action is a step-by-step guide to developing portlets using the Java Portlet
technology The text is complemented by numerous examples to demonstrate howdifferent features of the Java Portlet technology are used in developing portlets Thebook covers not only the core Portlet 2.0 API, but also goes beyond to cover leadingframeworks that simplify portlet development
Roadmap
The book is divided into three parts
Part 1 introduces the Java Portlet technology and includes chapters 1–6 If you’renew to portlets, you should read chapters in sequence
Chapter 1 introduces you to the world of portlets and web portals In this ter, you’ll learn what portlets and web portals are, and why they’re so important intoday’s world This chapter lays the foundation for learning the portlet conceptsdescribed in later chapters We’ll also look at how to install a Liferay Portal server,set up the Eclipse IDE and a portlet application’s project structure, and develop aHello World portlet
Trang 25Chapter 2 takes you an inch deep into the portlet world and presents a simple UserRegistration portlet This chapter introduces the portlet lifecycle and some of thecommonly used Portlet 2.0 classes and interfaces It also introduces container-runtimeoptions, which provide additional portlet container features to the portlets This chap-ter sets the stage for diving deep into the Java Portlet technology
Chapters 3 and 4 describe the Portlet 2.0 API in the context of a Book Catalog let In these chapters, we’ll look at the different request and response objects used inportlets and the specific features they provide We’ll see how JavaScript and CSS areprogrammatically added to portal pages, how portlet content is localized usingresource bundles, how portlets are secured, and how portlet content is cached We’llalso look at the details of the different container-runtime options defined by the port-let specification
Chapter 5 shows you how to develop an example Book Portal web portal usingLiferay Portal This chapter shows how a portal server’s built-in portlets can help min-imize the effort involved in building a web portal This chapter also shows how theLiferay Plugins SDK can be used to develop a custom theme and layout for a web por-tal Readers who are using the GateIn Portal with the examples in this book can refer
to appendix A, which describes how to develop a web portal using GateIn Portal Chapter 6 introduces portlet tag library tags, which are used for developing port-lets with JSP as the view technology Different portlet tag library tags are introduced inthe context of a Book Catalog portlet
Part 2 of this book shows you how to develop portlets using Spring Portlet MVC,Spring JDBC, and Hibernate This part includes chapters 7–9, and it’s recommendedthat you read chapters 7 and 8 sequentially
Chapter 7 introduces the Spring Framework and the classes and interfaces ofSpring Portlet MVC This chapter describes the Spring Portlet MVC architecture andlays the foundation for learning more advanced concepts in Spring Portlet MVC,and it uses a variety of examples to explain different Spring Portlet MVC concepts Chapter 8 takes a deep dive into the annotation-driven development support inSpring Portlet MVC and in Spring in general This chapter covers Spring’s form taglibrary, JSR 303 (Bean Validation), the Spring Validation API, dependency injectionusing JSR 330 and JSR 250, and Spring’s TestContext framework for unit and integra-tion testing All the concepts are introduced in the context of the example Book Cata-log portlet
Chapter 9 looks at how you can write database-driven portlets using the Spring
JDBC module and Hibernate This chapter also provides a quick introduction toaspect-oriented programming and transaction support in Spring The conceptsdescribed in this chapter are put to use while developing the example Book Cata-log portlet
Part 3 of the book covers advanced concepts in portlet development, includinginter-portlet communication, WSRP, personalization, portlet bridges, Ajax/Comet,
Trang 26and portlet filters This part of the book includes chapters 10–15, and there’s no need
to read the chapters in this part sequentially
Chapter 10 looks at the personalization support available in portlets and how it can
be used to personalize the content and behavior of a portlet In the context of theBook Catalog portlet, this chapter shows how preferences are defined for a portlet,saved into a persistent store, and later retrieved to personalize the content and behav-ior of the portlet
Chapter 11 looks at different techniques for inter-portlet communication, usingsessions, public render parameters, and events The examples in this chapter showhow each communication technique is implemented
Chapter 12 introduces Ajax and how it’s used for developing highly responsiveportlets The chapter looks at different Ajax frameworks, like jQuery, DWR, and Dojo,
to show how each one of them can be used to incorporate Ajax features in portlets.This chapter also looks at how Comet (or Reverse Ajax) is used for developing real-time portlets The chapter makes use of numerous code examples to demonstratethese concepts
Chapter 13 introduces you to the world of portlet bridges, which are used toexpose existing web applications as portlets The chapter shows how a JSF 2.0 webapplication and a Wicket web application can be exposed as portlets using port-let bridges
Chapter 14 looks at developing portlets that make use of portlet filters for pre- andpost-processing portlet requests and responses
Chapter 15 looks at how Web Services for Remote Portlets (WSRP) can be used by aweb portal to publish portlets to the external world, so that they can then be con-sumed by other web portals
Appendix A introduces the GateIn Portal and describes the steps required to ate an example Book Portal web portal
Appendix B shows how to configure Liferay Portal to use a MySQL database
How to use this book
This book contains numerous working examples that demonstrate how to developportlets using Portlet 2.0 and other leading frameworks, like Spring Portlet MVC,Hibernate, DWR, Spring JDBC, Dojo, jQuery, and so on The book contains CODEREFERENCE callouts to inform you when you should import an Eclipse project intoyour Eclipse IDE for reference I recommend that you install the Liferay Portal orGateIn Portal and try out the examples while reading the book, and that you refer tothe source code when it’s suggested in the text This approach will help you learnportal and portlet development more effectively
Who should read this book?
In writing this book, I haven’t assumed that you have any prior knowledge of the JavaPortlet technology or the different frameworks referenced here The concepts are
Trang 27described in such a way that readers who have prior knowledge of web applicationdevelopment using JSPs and servlets can easily understand the content
The different frameworks covered in this book, like Spring Portlet MVC, Spring
JDBC, Hibernate, Spring AOP, DWR, Dojo, jQuery, and so on, are gently duced, so that the example portlets can be easily understood even if you’re new tothese frameworks
If you have prior experience working with web portals using Portlet 1.0, you’llalso find this book useful, because it explains the new features introduced in Port-let 2.0 and how to go about creating portlets that make use of frameworks likeSpring Portlet MVC, Spring AOP, Spring JDBC, Spring Transaction, Hibernate, Dojo,jQuery, and DWR
Because the book provides complete coverage of Portlet 2.0’s features and tion with different frameworks, portal architects will also find this book useful forarchitecting solutions around Portlet 2.0
integra-Source code conventions
This book contains numerous examples that include portlet classes, XML tion files for portlets and portal servers, JSP pages, build.xml files for the Ant buildtool, and pom.xml files for the Maven build tool The code explained in the book tar-gets Liferay Portal server GateIn Portal–specific Eclipse projects additionally contain
configura-a README.TXT file that specifies GateIn Portal–specific changes made to the portletsdeveloped for Liferay Portal
In the text, a monospace typeface is used to denote code (JSP, Java, and XML) aswell as Java methods, JSP tag names, and other code elements
Java, HTML, and XML can all be quite verbose, and in many cases the originalsource code (available online) has been reformatted, adding line breaks and rework-ing indentation, to accommodate the available page space in the book In rare cases,even this was not enough, and listings include line continuation markers (➥) Additionally, comments in the source code have been removed from the listingspresented in the book Code annotations accompany many of the source code listings,highlighting important concepts In some cases, numbered bullets link to explana-tions in the text following the listing
Software requirements
To deploy and run the example portlets in this book, you need to install GateIn tal 3.1, Liferay Portal 6 CE GA3, or any Portlet 2.0–compliant portlet container.GateIn Portal 3.1 and Liferay Portal 6 CEGA3 are freely downloadable and have lowmemory footprints The examples in this book make use of Liferay Portal andGateIn Portal, which come bundled with the Tomcat server
Chapters 3 and 4 make use of Jetspeed and GlassFish Server with OpenPortal let Container to show that support for some of the Portlet 2.0 features varies from oneportal server to another If you want to test the example Book Catalog portlet
Trang 28described in chapters 3 and 4, you’ll need to install Jetspeed 2.2.1 and GlassFishServer 3.0.1 with OpenPortal Portlet Container 2.1
To run the example portlets in chapter 9, you’ll also need to install the MySQL
database and HeidiSQL client, the details of which are provided in appendix B
Source code downloads
The source code for all the examples in this book is available from Manning’s website: www.manning.com/PortletsinAction/ The examples have been provided forboth GateIn Portal and Liferay Portal servers, and they’ve been tested on GateIn Por-tal 3.1 and Liferay Portal 6 CEGA3, but they’ll work on any Portlet 2.0–compliant port-let container with little or no modification
The source code explained in this book is for Liferay Portal Because GateIn Portalrequired some minor changes to the source code, these changes have been recorded
in the README.TXT file that you’ll find in the Eclipse projects for GateIn Portal
To run the examples, you can download the Tomcat bundle for GateIn Portal orLiferay Portal and deploy the example portlets as described in chapter 1 (for LiferayPortal) and in appendix A (for GateIn Portal)
The source code for the book is divided into separate Eclipse projects, and thenames of the folders reflect the chapter to which the example belongs For instance, ifthe folder name is ch7_Controllers, the source code is for chapter 7 Each examplecan be built by using either Ant or Maven, and the steps required are explained inchapter 1
Author Online
Purchase of Portlets in Action includes free access to a private web forum run by
Man-ning Publications where you can make comments about the book, ask technical tions, and receive help from the author and from other users To access the forum andsubscribe to it, point your web browser to www.manning.com/PortletsinAction Thispage provides information on how to get on the forum once you’re registered, whatkind of help is available, and the rules of conduct on the forum
Manning’s commitment to our readers is to provide a venue where a meaningfuldialog between individual readers and between readers and the author can take place
It is not a commitment to any specific amount of participation on the part of theauthor, whose contribution to the Author Online forum remains voluntary (andunpaid) We suggest you try asking the author some challenging questions lest hisinterest stray!
The Author Online forum and the archives of previous discussions will be ble from the publisher’s website as long as the book is in print
Trang 29about the cover illustration
The figure on the cover of Portlets in Action is captioned “Le petit fermier,” which
means smallholder or the owner of a small farm, just large enough to support onefamily The illustration is taken from a nineteenth-century edition of SylvainMaréchal’s four-volume compendium of regional dress customs published in France.Each illustration is finely drawn and colored by hand The rich variety of Maréchal’scollection reminds us vividly of how culturally apart the world’s towns and regionswere just 200 years ago Isolated from each other, people spoke different dialects andlanguages In the streets or in the countryside, it was easy to identify where they livedand what their trade or station in life was just by their dress
Dress codes have changed since then and the diversity by region, so rich at thetime, has faded away It is now hard to tell apart the inhabitants of different conti-nents, let alone different towns or regions Perhaps we have traded cultural diversityfor a more varied personal life—certainly for a more varied and fast-paced technolog-ical life
At a time when it is hard to tell one computer book from another, Manning brates the inventiveness and initiative of the computer business with book coversbased on the rich diversity of regional life of two centuries ago, brought back to life byMaréchal’s pictures
Trang 31In this part of the book, you’ll learn the basics of web portals and Java portlettechnology As you progress through these chapters, you’ll discover how portlettechnology simplifies the development of web portals Java portlets are deployed
in a portlet container, which is similar to a servlet container, so a substantial tion of this part of the book focuses on the portlet container’s features and howyou can use them to implement your portlets Toward the end of this part, you’lldevelop a real-world web portal example to get a feel for web portals
Trang 33customizable themes and features that allow users to control what content is sented and how it’s presented
The lack of a standard approach and technology to address user-experiencerequirements, such as personalization, customization, and content aggregation inweb applications, led to ad hoc ways of implementing these features The result wasmaintenance nightmares, lost developer productivity, and longer turnaround timefor incorporating new features With the arrival of the Java portlet technology, this
This chapter covers
■ An over view of por tals and the Java por tlet
technology
■ Installing and using Liferay Por tal
■ Setting up the Eclipse IDE and creating the
project structure
■ Developing a Hello World por tlet
Trang 344 CHAPTER 1 Introducing portals and portlets
has changed The Java portlet technology provides a standard approach to ing user-experience features in web applications
The Java portlet technology isn’t a standalone technology, and using JSPs andservlets (along with portlets) in portal development is common The Java portlettechnology not only helps you quickly build a web portal but also provides serviceorchestration, in which distinct services can be integrated seamlessly at the userinterface layer, allowing businesses to quickly adapt to changes
This chapter will first introduce you to web portals and the portlet technology, and
to the infrastructure you need to deploy a web portal that uses portlet technology.Most of the latter half of this chapter is dedicated to quickly getting started with Life-ray Portal and setting up the Eclipse IDE Towards the end of this chapter, you’ll seehow to deploy a Hello World portlet on Liferay Portal
The concepts behind portlets can be best understood through deploying exampleportlets on a portal server and adding them to a portal page We use Liferay Portal inthis book because of its ease of installation, intuitive interface, low memory footprint,and more importantly, you can download and use the Community Edition of LiferayPortal for free This book touches upon some of the features of Liferay Portal at ahigh level, but it shouldn’t be considered a reference or user guide for Liferay Portal NOTE Even though this book uses Liferay Portal for deploying and runningportlets, the concepts covered in the book are generic and can be used fordeveloping portlets for any Portlet 2.0–compliant portal server
If you’re already familiar with the concepts behind portals and portlet technology, youmay want to skim or skip this chapter If you’re new to portlets, this chapter will giveyou a solid foundation for the rest of the book
As portals and portlet technology go hand in hand, we’ll first look at what a webportal is and how portlets can be used to develop a web portal
Everyone who’s been using the internet knows something about portals It’s not a newconcept, but there was no formal definition until recently
A portal is a collection of mini web applications, called portlets A portal supports
features like personalization, content aggregation, authentication, and customization.Portlets act as windowed web applications within the portal, and each window in a por-
tal web page (called a portal page) represents a portlet.
To get a feel for portals, you can visit the iGoogle portal (http://www.google.com/ig) Figure 1.1 shows the iGoogle portal home page after a user logs into it.You can see portlets showing emails from Gmail, headlines from CNN, contentfrom YouTube, and so on The portlets can be personalized by users to change thenumber of emails displayed in the portlet, the number of CNN headlines theywant to view, the location they want to receive RSS feeds from, and so on Userscan drag and drop these portlet windows on the portal page to customize the way
Trang 35NOTE I’ve referred to portlets as mini web applications because they provide
limited information and features to the user compared to the original webapplications they represent For example, in figure 1.1, the Gmail portlet dis-plays email and provides options to compose or delete emails, but it doesn’tprovide an option to add emails to your tasks list, which is provided by theoriginal Gmail web application
The core business functionality provided by a portal is no different from what a set ofdistinct web applications would provide In figure 1.1, the content (information orservice) provided by the Gmail, YouTube, and CNN portlets is also provided by theGmail, CNN, and YouTube applications
But if the business functionality remains the same, what’s the business value increating a portal? In figure 1.1, the information displayed to the user comes fromdisparate data sources (as depicted in figure 1.2), and the portal aggregates theinformation to provide a consolidated view to the user
The use of portals to aggregate content from different sources results in increasedefficiency for the user, and an enriched user experience, because the user doesn’tneed to go to distinct web applications to access the content In figure 1.2, the portlets
Figure 1.1 The iGoogle home page containing portlets that show information from different sources: CNN, YouTube, Gmail, and so on The portlets display the most relevant content and provide limited features to the user, in contrast to full-fledged web applications.
Trang 366 CHAPTER 1 Introducing portals and portlets
on the iGoogle portal page display the most frequently accessed information or tures from the applications they represent
fea-NOTE Developing a web portal makes good business sense if you need togather and present information from various data sources, applications, andsystems to users based on their identity It’s expected that the user experiencewill be enhanced by a single point of entry to the information, and by the flex-ibility to customize and personalize the information that’s provided
Now that you know about portals, let’s take a look at the benefits of using portals,compared to web applications, for content aggregation and personalization
Web portals provide benefits beyond those of a group of distinct web applications thatserve content In this section, we’ll look at how end users access content from differ-ent information sources using distinct web applications, and how web portals and webapplications can coexist to take the user experience to new heights
For instance, a user might access content from different sources by directly ing different web applications, or by accessing those web applications from an intra-net website, or by using a combination of web portals and web applications
access-1.2.1 Enriched user experience
Let’s say that as an employee of an organization you need to frequently accessorganization-specific business-to-employee (B2E) applications (like time card, helpdesk, knowledge management, and service request applications) so you can keeptrack of missing time cards, recently published articles, closed help desk tickets, and
so on These different web applications have their own data sources, and you’d usually
Figure 1.2 Portals aggregate content from different information sources
The portlets on the iGoogle portal page generate content for the page by
retrieving information from the CNN, YouTube, and Gmail applications.
Trang 37Benefits of web portals
need to go to each of these different applications to access this information Thisinteraction between employee and B2E applications is represented in figure 1.3 This isn’t an optimal way of accessing information and services, because you need
to go to different web applications and authenticate each time An intranet site thatprovides a single sign-on feature and access to all these different applications would
be a better solution
Suppose the organization takes a step ahead and provides a single sign-on solutionand access to the different web applications from an intranet site, as represented infigure 1.4 By providing the single sign-on feature, the organization has provided easyaccess to the B2E applications, but you still need to filter the information that interestsyou For example, if you’re interested only in automobile-related articles, you’ll have
to search for the articles in the knowledge management application; if you’re onlyinterested in your open help desk tickets, you’ll need to search for them in the helpdesk application; and so on
These individual B2E applications may provide some level of personalization andcustomization based on your identity and preferences, but this approach still fails toprovide a unified view of information and easy access to services offered by different
B2E applications For instance, you still need to go to the help desk application toaccess its information and services
The ideal scenario for an employee is to view information and access the mostcommonly used services from distinct B2E applications in a single application Thisscenario is represented in figure 1.5 and is achieved using intranet portals Here, the
Figure 1.3 In this scenario, the user interacts with multiple web applications
to access content A separate web application exists to access content from
each of the distinct sources of information.
Trang 388 CHAPTER 1 Introducing portals and portlets
Figure 1.4 The organization’s intranet makes it easy for users to access different web applications by redirecting users to the original web applications In this scenario, the user is still interacting with individual web applications for information and services.
Figure 1.5 The organization’s intranet portal gathers content from different data sources, which means that users don’t need to access different web
applications for information or services In figure 1.4, the intranet website
simply redirected users to the original web applications, but when using portals, the user is taken to the original web application only if little-accessed
information or services are requested by the user.
Trang 39Benefits of web portals
user mostly interacts with the portal, and in some cases also with the original webapplication For instance, the portal directs the user to the knowledge managementweb application if certain features or details are requested by the user
Usually, portals provide users with the most-used features of the original web cation, and when less-used features are requested, the portal redirects the user to theoriginal application The portal may not even display the least-used features but mayinstead provide an option to visit the original application
Some of the web portal’s functionality may be built into the portal itself, so that noexternal web applications or systems are involved For instance, if you don’t have aseparate content management system available, you could develop it as part of yourweb portal
NOTE The design of existing systems greatly affects how quickly a businesscan start using portals In figure 1.5, information for the knowledge manage-ment and time card applications comes from the databases that were used bythese applications, which requires rewriting the business logic In contrast,the help desk application’s business logic is accessed using Web Servicesbecause the application was designed as a set of services that can be reused byother applications—a service-oriented architecture (SOA) approach It’s rec-ommended that applications make use of SOA internally, because it allowsyou to expose business functionality as a service in the future, saving you theeffort of redoing the business logic
Portlets in a web portal provide limited content compared to the dedicated web cations they represent, which means portals have to be used along with web applica-tions to provide content to the user
appli-1.2.2 Unified information view
Web applications generally target a part of the business process and not the completebusiness For example, there would be separate web applications for customer man-agement, inventory, order processing, and so on These web applications give a dis-jointed view of the business, because the inventory application doesn’t know aboutorders placed, and the customer management application doesn’t know about theinventory status
These web applications don’t need to know about information managed by otherweb applications, but a business user might need a unified view of the business A
Portals complement web applications
Portals aren’t a replacement for web applications but are meant to extend the tionality of existing web applications Portals gather relevant content from theexisting information systems and display it to users based on their identity andpreferences When certain information or features are requested by the user, theportal redirects the users to the original web applications
Trang 40func-10 CHAPTER 1 Introducing portals and portlets
web portal can bridge the information gap between these individual web tions by bringing information together from the different data sources used by theseweb applications, and presenting it to a business user, providing the unified viewthat’s required
The portlets in a web portal are dynamic, and they may interact with each other toshow relevant information in response to user actions For instance, in a Weather por-tal (which contains Location and Weather portlets), if a user selects a city from theLocation portlet, the Weather portlet updates the content to display the weather fore-cast for the selected city In contrast, web applications communicate with each otherusing databases or messaging middleware The result of such communication isn’timmediately visible and requires users to access the web applications separately to viewthe effects of the communicated information
A portal consists of multiple portal pages, just as web applications consist of multipleweb pages The only way content can be added to a portal page is via portlets
A portlet is a pluggable user interface component that provides specific content, which
could be a service or information from existing information systems Portlets providethe user interface of the portal by accessing distinct applications, systems, or datasources and generating markup fragments to present their content to portal users.Some examples of portlets are a Weather portlet that provides weather informationfor a city by accessing a Yahoo! Weather RSS feed, or a Help Desk portlet that displaysthe pending help desk tickets from a database
The primary responsibility of a portlet is to generate a markup fragment (such as
HTML, XML, or WML), which is then displayed on a portal page within a window,
called a portlet window A portal page usually displays multiple portlets in distinct
port-let windows, each with its own title and set of buttons to change its look and feel, set itspreferences, and maximize, minimize, or remove the window
Figure 1.6 shows what a portlet window looks like when rendered on a portal page.The options available for a portlet, such as changing window state, preferences, and
One size doesn’t fit all
Portals aren’t the answer to every business requirement; organizations should sider carefully whether there is a business case for developing a portal If the busi-ness requirement doesn’t require gathering content from distinct informationsystems to loosely integrate disparate systems, the business should considerdeveloping independent web applications to meet the business requirement
con-The personalization and customization features of portals are important from theuser’s perspective From the business’s perspective, the most important require-ment to consider is content aggregation