31,19 €
The Seam framework from JBoss allows developers to use JSF, Facelets, EJB, and JPA to write conversational web applications. But you will first have to learn how these standard technologies are integrated using Seam and how they can be built upon using additional Seam components. If you need to build a Java web application fast, but don't have time to learn all these complex features, then this book is for you.
The book provides a practical approach to developing Seam applications highlighting good development practices. It provides a complete walk through to develop Web applications using Seam, Facelets, and RichFaces and explains how to deploy them to the JBoss Application Server. You can start using key aspects of the Seam framework immediately because this book builds on them chapter by chapter, finally ending with details of enterprise functionality such as PDF report generation and event frameworks.
First, the book introduces you to the fundamentals of Seam applications, describing topics such as Injection, Outjection and Bijection. You will understand the Facelets framework, AJAX, database persistence, and advanced Seam concepts through the many examples in the book.
The book takes a practical approach throughout to describing the technologies and tools involved. You will add functionality to Seam applications after you learn how to use the Seam Generator RAD tools and how to customize and fully test application functionality. Hints and tips are provided along the way of how to use Seam and the JBoss Application Server.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 289
Veröffentlichungsjahr: 2009
Copyright © 2009 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: April 2009
Production Reference: 1200409
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-847195-92-0
www.packtpub.com
Cover Image by Leo Cornall (<[email protected]>)
Author
David Salter
Reviewers
Cameron Ingram
Daniel Roth
Wouter van Reeven
Acquisition Editor
Sarah Cullington
Development Editor
Nikhil Bangera
Siddharth Mangarole
Technical Editor
Rakesh Shejwal
Copy Editor
Sumathi Sridhar
Indexer
Hemangini Bari
Production Editorial Manager
Abhijeet Deobhakta
Editorial Team Leader
Akshara Aware
Project Team Leader
Lata Basantani
Project Coordinator
Neelkanth Mehta
Proofreader
Dirk Manuel
Production Coordinator
Dolly Dasilva
Cover Work
Dolly Dasilva
David Salter is an enterprise software architect who has been developing software professionally since 1991. His relationship with Java goes right back to the beginning, using Java 1.0 for writing desktop applications and applets for interactive web sites. David has been developing Enterprise Java applications using both the J2EE standards and open source solutions since 2001. David runs Develop In Java, a Java community web site, for all levels of Java developers.
First and foremost, I would like to thank my wife and family for putting up with my many hours at the computer whilst writing this book. Special thanks and love to my wife for all her encouragement and support.
I'd also like to say thank you to all the people at Packt Publishing for helping me with this book. Thank you Sarah for encouraging and believing in me from the beginning. Thanks also to Neelkanth and Rakesh for your hard work helping me to complete the book.
Finally, thanks to Gavin King and JBoss, without whom there would be no book.
Cameron Ingram started in the software industry in the 90's. In the last few years, he has been concentrating on RIA with a special emphasis on Seam and Flex, and has been a contributor to the GraniteDS project. Cameron has presented at various conferences, ranging from monitoring application environments to implementing an ESB. He currently lives in St. Petersburg, FL with his wife and two daughters, and cooks a mean set of ribs. Cameron Ingram currently works at PSCU Financial Services as a Senior Software Architect.
Tracy, Ally, Camille, thank you for your love and support—it always helps me through the long hours that sometimes come with this profession. And to Joy, without your guidance and leadership I wouldn't be where I am today.
Daniel Roth is a software developer from Sweden, who has been working in web development for almost ten years. He has a Master's degree in Computer Science and Engineering from Chalmers University of Technology in Gothenburg. Since 2007, when he first was introduced to JBoss Seam, he has worked with it both professionally and personally. Today, Daniel works as a Seam committer in his spare time, trying to make Seam even better.
I'd like to thank Fredrik Wendt for converting my preferences from PHP to Java for web development, Carl-Magnus Nordin, Bengt Fredin and David Rosell for introducing me to Seam, the awesome Seam community for all of the support, and of course my lovely girlfriend Sofia.
This book provides a complete walk-through of developing Web applications using Seam, Facelets, and RichFaces, and explains how to deploy them to the JBoss Application Server.
This book introduces you to the fundamentals of Seam applications, describing topics such as Injection, Outjection, and Bijection. You will understand the Facelets framework, AJAX, database persistence, and advanced Seam concepts, through the many examples explained in the book.
A practical approach is taken throughout the book to describe the technologies and tools involved. You will add functionality to Seam applications after you learn how to use the Seam Generator RAD tools and how to customize and fully test application functionality. Hints and tips on how to use Seam and the JBoss Application Server are provided along the way.
Chapter 1 provides an overview of the Seam Framework, and describes the benefits that we, as Java developers, will gain by using the framework. We learn that Seam is much more than a framework, and that it comes packed with support for numerous other features.
Chapter 2 teaches you how to develop applications using Seam, and explains some of the features discussed in previous chapter. In this chapter, we will learn the basic structure of a Seam application and learn more about Seam components. We will also see exactly how Seam bridges the gap between the Web tier and the Server tier.
Chapter 3 takes you through page navigation using Seam page flows. We also see how we can define page flow within the pages.xml file of our applications by defining both static rules and rules encompassing JSF expression language.
Chapter 4 shows you why Facelets is recommended, and what it offers over JSP. We'll also look at the SeamGen tool and see why this is a much better way of creating Seam applications and building scripts. Finally, we bring both SeamGen and Facelets together and re-create the Vacation Planner project that we wrote in Chapter 3, (realizing in the course of doing so how much easier and more advanced it is), using these technologies
In Chapter 5, we take a look at TestNG and see how it can be used to build sets of test suites. We have a look at how Seam provides excellent facilities by allowing us to perform testing of our applications, at the class, Seam component, and user interface levels.
In Chapter 6, we take a look at RichFaces and learn that it's a JSF component library that allows us to easily build rich user interfaces within web applications. This chapter explains how Seam is fully integrated with RichFaces, and that applications generated by SeamGen require no special configuration to allow RichFaces to be used. This chapter also lists all of the components available within RichFaces.
Chapter 7 introduces database persistence with Seam. We take a closer look at how SeamGen helps us to create and configure our applications, allowing test, development, and production profiles to be configured.
Chapter 8 takes a closer look at what exactly a conversational application is and why they make web application development easier and more functional. We also take a look at different component scopes and see why they are important to Seam.
In Chapter 9, we take a look at AJAX and how it can be applied to Seam applications. We also take a closer look at the two different AJAX technologies within the Seam framework: Seam Remoting and AJAX4JSF.
Chapter 10 discusses how security is implemented within a Seam application highlighting the most common features, such as logon pages, user access rights, CAPTCHAs, and so on, which are used to secure Seam applications. We also highlight some of the more advanced security features that can be used.
Chapter 11 walks through some of the more advanced features of Seam, such as internationalization, URL rewriting, PDF document generation, and so on, and also discusses how these can be used within our web applications.
This book is for Java EE application developers who are new to Seam and who are interested in developing with Seam 2.x.
You need a basic understanding of Java EE and must also be aware of EJB3, although you do not need to know it in detail. Experience with JBoss AS would be an advantage, but all you really need is to be comfortable using any application server. Knowledge of AJAX and JavaScript would also be beneficial, although not necessary.
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "The <page> element defines the pages to which the enclosed navigation rules are applicable."
A block of code will be set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items will be shown in bold:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: "The following action that is within this class is executed when the user clicks on the Select button on our web page."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply drop an email to <[email protected]>, and mention the book title in the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note via the SUGGEST A TITLE form on www.packtpub.com or by sending an email to <[email protected]>.
If there is a topic that you have expertise in and that you are interested in either writing or contributing to a book on, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Visit http://www.packtpub.com/files/code/5920_Code.zip to directly download the example code.
Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration, and help us to improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to any list of existing errata. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
Enterprise Java development has changed dramatically in recent years, particularly with the introduction of the Java Enterprise Edition version 5 (Java EE 5) specifications in early 2006. One of the main goals of Java EE 5 was to make the development of enterprise Java applications easier through the use of annotations. Annotations were first introduced to the Java platform with Java SE 5, and allow information about Java classes to be embedded within the Java source files themselves, rather than being stored in external XML files.
Java EE 5 promotes a tiered development pattern by using Session Beans to develop server-side code, and Java Server Faces (JSF) to develop web based user interfaces. The Java EE specification, however, doesn't specify how these two technologies are to interoperate. This is where the Seam Framework fits in, helping to bridge the gap between server-side programming and web development.
In this chapter, we will learn what Seam is and why we, as Java enterprise developers, should use Seam. We'll take a brief look at why Seam is different when compared to the previous frameworks used by Java enterprise developers, and then we'll look at how we can install Seam and the JBoss Application Server. Finally, we'll run some sample applications to confirm whether we've got the infrastructure installed correctly, so that we can learn all about the Seam framework.
As most Java developers will know, there are many web frameworks available to the Java developer. But why Seam? Before we discuss what exactly is Seam and what makes Seam a different framework, let's take a very brief look at the history of the earlier web frameworks.
With the increased popularity of the Model-View-Controller (MVC) pattern and frameworks such as Struts, Java web development suddenly got a whole lot easier. With de facto standard frameworks, developers were able to concentrate on their application logic rather than think about the plumbing of how to develop scalable database-driven web applications. However, with these frameworks, developers still had to think about HTTP requests and responses, and developing effective web-based user interfaces implied writing HTML code.
The next evolutionary stage in web development came in 2004 when the Java Server Faces (JSF) technology was created. JSF uses a component-based approach to web development, unlike previous frameworks such as Struts. This component-based approach opened up the market for drag-and-drop style development environments. If a developer wanted to have a table of results shown on a web page backed by database queries, this could be achieved using drag-and-drop and minimal coding effort. If, for example, the developer wanted to change the user interface to allow the table of results to have clickable column headings, this could typically be achieved by setting a few properties within the IDE rather than having to write lots of Java code and HTML. Oracle's JDeveloper and Sun's Java Studio Creator, amongst others, offered GUI builders for web applications—the type of technology previously found only in GUI designers for desktop applications. All of the modern IDEs (Eclipse, NetBeans, and IntelliJ IDEA) now support this type of drag-and-drop support for JSF development. Examples of such a type of support in Eclipse (using JBoss Tools) and NetBeans 6.1 are shown in the following screenshots.
We've now seen how JSF came to be, and how web development used to be tricky and cumbersome, but how does Seam fit into this web development landscape? What is Seam, and why is it different? In simple terms, Seam is a web framework that makes developing web applications simpler. Because they have become standard with Java EE 5, Seam makes extensive use of annotations to help us achieve this goal. All of the annotations used within Seam applications take common-sense defaults with the aim of cutting down on the amount of configuration required by annotations. This use of default values is called configuration by exception. In most cases, the default values for annotations are correct and applicable to the task at hand, meaning that less configuration data has to be entered into the application code. Of course, it is still possible (and necessary) to change configuration values and add parameters into annotations. But in most cases, configuration by exception helps cut down on the amount of configuration required.
The use of annotations in Seam does not completely remove the need for XML configuration. However, it is greatly reduced when compared to other frameworks such as Spring, Struts, or JSF. With the exception of defining page flows in XML files, Seam rarely uses XML configuration. The XML configuration in these cases is generally very similar among applications, and is not considered a large part of application development.
With the Java EE 5 framework, Dependency Injection has become a standard feature of enterprise application development. Within Java EE 5, Dependency Injection allows components to be automatically set within classes without the need for the developer to call any setter methods. For example, Session Beans can automatically be looked up using the @EJB annotation, or the Entity Manager Factory can be set using the @PersistenceUnit annotation. Seam extends the Dependency Injection capabilities provided by Java EE 5 and allows Seam components to be both injected into and outjected from other components. This facility to perform both Dependency Injection and Dependency Outjection is more commonly called Dependency Bijection, and will be discussed fully in Chapter 2.
The Seam Framework is a stateful framework. Seam components can be declared to have different contextual scopes. These scopes range from stateless (having no state) through to long running scope or application lifetime scope. Frameworks such as Spring and Struts are stateless frameworks in the sense that they do not offer facilities to define scope for components. All of these frameworks allow components to be cached using various caching strategies, but Seam component scope further allows different components to be declared with different levels of scope. This is discussed in depth later in this book.
Seam components are used to define entities and classes that manage entities within an application. Seam does not impose any design patterns on components. We do not need to extend Seam classes or implement Seam interfaces to define Seam components. A Seam component can be any POJO (Plain Old Java Object). In this book, however, we will use Session Beans (both stateless and stateful) as Seam components. This will be useful because of the benefits (security, transactions, pooling, and so on) that Session Beans provide us. With Seam we don't have to use Session Beans as Seam components. A Seam component can be just as easily declared a POJO as can it be declared a Session Bean.
Seam is supplied with, and fully integrates with, the RichFaces component library. RichFaces provides many user interface components, and is described fully in Chapter 6.
JSF didn't really take off as a development model until it became the standard web framework used within Java EE 5 applications. The first versions of Seam used JSF with JSP as the view technology, but this is no longer the view technology recommended by JBoss, and has been superseded by Facelets. Seam also allows other view technologies, such as Flex, GWT, and Wicket, to be used. However, these technologies are not covered in this book. JSF or JSP can still be successfully used as the view technology for Seam applications, and we will be using them in the next few chapters of this book, to learn the basics of Seam. We will discuss Facelets in Chapter 4, when we have a good understanding of Seam, and will see what it offers that JSF does not.
Over the past few years, agile techniques have turned favorable, including Test Driven Development and Unit Testing. Traditionally, testing web applications has been a fairly complex task. However, Seam provides a simple yet effective mechanism for unit testing that includes not only testing our application logic, but also testing the user interface logic. In Chapter 5, we will detail how we can successfully test our Seam applications and provide good test coverage by using the TestNG test tool.
So far, we have discussed Seam as though it were only a web framework. Seam promises to be much more than that. At the beginning of this chapter, we learned that Seam helps bridge the gap between server-side programming and web programming. Well, what exactly does this mean?
In traditional J2EE, Java EE 5 web applications, database tables are typically modeled as either Entity Beans or Entities with Persistence. The typical flow of events in a database-driven web application would be:
This technique of detaching objects and displaying "dumb" data works quite well for small domain models that don't have many relationships between objects. However, when there are complex relationships, the web client cannot always access the entire domain model, as only certain aspects of the model have been serialized to the client. This can lead to lazy initialization errors, where clients try to access parts of our data model that have yet to be initialized from the database. Seam alleviates this problem by allowing Java EE 5 Persistent Entities to be used within the web tier. In Java EE 5, Persistent Entities are simple POJOs. Hence, full access to an applications domain model is available on the web tier within Seam applications.
Seam provides the Hibernate Validator classes as a part of the framework, and these provide an additional level of entity validation over what the Java EE framework provides as standard. We can therefore validate our entity properties easily in the user interface, to ensure that invalid values are not entered into our domain model.
We will discuss database persistence in depth in Chapter 7.
More often than not, web applications require users to traverse through several pages before completing a given action. Consider, for example, applying for motor insurance. As users of motor insurance web sites, we have to enter our name, address, the use of our motor vehicle, the type of insurance required, and so on, before we can finally get a quote for insurance. Typically, this type of procedure is mapped out as a series of web pages with the Previous and the Next buttons. How many times have you accidentally closed the browser in the middle of applying for or buying something on the Internet? How many times have you pressed the Back button and lost all of the submitted data that you had just entered? Seam provides the solution to these problems in terms of conversations, which we'll discuss in Chapter 8. These conversations can be anything from a simple one-page request/response conversation through to a multipage conversation that lasts several hours or longer!
A conversation is an example of how Seam works as a stateful framework, with a conversation being one of the different levels of component scope.
With the advent of modern web applications and AJAX, users expect a higher level of interactivity within their web applications. The distinction between desktop applications and web applications is becoming increasingly blurry. Manually crafting JavaScript code can be time-consuming and prone to error, and isn't always the best way to add AJAX functionality to an application. The Seam Framework provides AJAX support via tight integration, with the AJAX4JSF library helping to alleviate the issues with writing the JavaScript code manually. We will discuss AJAX4JSF support in Chapter 9.
Most applications need some sort of security access to restrict application functionality between users. Sometimes, a simple level of security access is required, whereby, only logged-on users can access certain pages—for example, so that only registered and logged-on users can post comments on a blog. Sometimes, this level of security isn't sufficient and a role-based security model is required. For example, again in a blog application, only users with the editor role would be able to edit and delete comments. You'll be pleased to know that Seam provides both user-based and role-based security mechanisms. We'll discuss these in detail in Chapter 10.
On top of all of these features that the framework provides, Seam is also supplied with a tool for rapidly generating application skeletons. The SeamGen tool allows application skeletons to be built via a series of interactive questions that are asked to the developer. Throughout the course of this book, we'll first learn how to write Seam applications without using the SeamGen tool, so that we can get a good understanding of the different parts of a Seam application and how they all fit together. Only when we have a solid understanding of what constitutes a Seam application, we'll introduce the SeamGen tool and show the benefits and performance gains that it provides.
So, how is Seam different from other web frameworks, and why should we learn a new technology?
Seam is a stateful, conversational framework, as opposed to being a stateless framework such as Spring or Struts, which provide rapid application development tools that wouldn't be unfamiliar in a RAD environment such as Ruby on Rails. Seam integrates different aspects of Java EE, providing us with a unified development model where we don't need to worry about redundant patterns such as DTOs. We can access our domain model and data model and all of their classes from within our web tier, without worrying about detached classes and lazy initialization errors. Seam uses the Hibernate Validator classes to provide additional validation on classes over what Java EE provides as standard. We could use JPA as our persistence provider if we wished, but by no means is this mandatory.
We can use as many or as few aspects of the Java EE specification as we wish—a simple Seam application could use Servlet and JSF, and be deployed on Tomcat. Alternatively, we could use more advanced Java EE features such as Session Beans and JPA, and deploy our applications to full Java EE Application Servers such as JBoss, GlassFish, or Weblogic. Seam components don't need to extend any Seam classes or implement any Seam interfaces—they can be simple POJOs or Session Beans.
Finally, Seam requires a minimal XML configuration, with the majority of configuration being required as Java annotations, where the default values are usually the correct ones.
To compile and build Seam applications, we need JDK 5.0 or above installed. We also need Apache Ant 1.6 or above (http://ant.apache.org) installed, as we use this as the build tool for the projects that we build throughout this book. Here, we do not describe how to install Apache Ant as there is full documentation for this on the Apache Ant web site.
To run our Seam applications, we need to deploy them to a Java Application Server. Throughout this book, we will be using the JBoss Application Server version 5.0. Many other application servers can be used for deploying and running Seam applications, such as WebSphere, WebLogic, GlassFish, or even Tomcat. However, we will concentrate solely on the JBoss Application Server.
The recommended version of Java for running Seam applications is 5.0. As at the time of writing this book, Seam and the JBoss Application Server have not been fully tested with JDK 6.0.
The JBoss Application Server can be downloaded from the JBoss web site at http://www.jboss.org/jbossas/downloads/.
Throughout this book, we will be using JBoss Application Server version 5.0.0.GA. This version is licensed under the LGPL license. Please check and read the license agreement before downloading the software. When downloading JBoss, make sure you download the application server (with a name similar to JBoss-5.0.0.GA.zip) rather than the source code (which has a name similar to JBoss-5.0.0-src.tar.gz). As the application server is written in pure Java, there is only one download for all operating systems. Hence, regardless of whether you are developing on Windows, MaxOS X, or Linux, the download is the same.
After downloading the JBoss Application Server, use your favorite unzipping tool to extract the JBoss Application Server. Once unzipped, you should find the directory structure of the application server to be as shown in the following screenshot.
The JBoss Application Server is started on Windows by executing the <jboss_home>/bin/run.bat command, where <jboss_home> is the directory into which you have installed JBoss (for example, C:\jboss-5.0.0.GA).
The run.bat application can be started with different command switches to start JBoss in different configurations. The default configuration is correct for our Seam applications throughout the course of this book. So, the easiest way to start JBoss is by double-clicking run.bat within an explorer window.
Once started, the JBoss Application Server window will contain a log of all of the startup events that have occurred, and will appear as shown in the following screenshot. If this window indicates any errors upon startup, check whether you have downloaded and installed your JDK correctly before proceeding. Depending upon your hardware configuration, starting the application server can take anywhere between 20 seconds and a few minutes.
To shut down the JBoss Application Server, we can simply press Ctrl+C within the application server console window.