About this Book – Seam in Action

About this Book

If you’re ready to become an expert on Seam, I can guarantee you that this book will get you there. I don’t use terms that confuse you just to make myself feel smart. I don’t say “trust me on this; it will all work out.” I don’t distract you with an outline of the next chapter when you’re trying to focus on the current material. And especially, I don’t sprinkle @In and @Out annotations over a class and expect that you’ll know what they will do. Nope. I lay down the facts. I show you the steps. I reveal the logic. I diagram the flow. What I like most about programming is that each thing happens for a reason. The exciting challenge is learning what that reason is and then turning around and discovering how to make practical use of it. Some areas of Seam are hard to get, I’ll admit. But trust that with guidance, you will get it. Never settle for less than the facts, and don’t give up!

Not only do I teach you how Seam works, I also teach you the how and the why so you can go off and teach Seam to others. I’ve traveled into each and every corner of Seam, and I want to share with you what I’ve experienced to motivate you to travel there yourself. I want to give you what Seam gave me: the ability to reach my true potential as a developer. This is the best resource to help you understand Seam without gaps.


The goal of this book is to get you started with Seam quickly. It’s divided into four parts. The first part does a flyover of Seam and gets you ready to learn about it. The second part focuses in on the core concepts until you can see the blades of grass. The third part studies Seam’s state-management solution and Java persistence support. The last part teaches you to make your application secure and stand above the competition. Best of all, you get to have fun.

Chapter 1 answers three questions: What is Seam? Why was Seam created? What does a Seam application look like? The chapter explains how Seam fits into the Java EE landscape and enumerates ways it extends the platform to make it more accessible and pertinent. You see a basic Seam application, which provides an overview of what is to come.

Rather than diving directly into the fundamentals of Seam, Chapter 2 steps you through setting up a Seam project. Not only does this give you an environment for testing the Seam concepts covered in the remainder of the book, it leaves you with a complete CRUD application that supports incremental hot deployment of changes.

Because JSF is the primary view framework in Seam, Chapter 3 provides a glimpse of it, identifies its weaknesses, and shows how Seam improves it. You study the page-oriented enhancements to JSF that Seam provides and get a high-level overview of how Seam involves itself in the JSF life cycle. By the chapter’s end, you should appreciate that the only reasonable way to develop using JSF is with Seam.

Chapter 4 explores the heart of Seam: the contextual container. You learn what a Seam component is, how it differs from a component instance, the palette of scopes in which you can store instances and other context variables, and how Seam manages the component life cycle. You get a feel for using annotations to control the application. You also learn ways to access components and when they are instantiated.

Seam’s central switchboard, the component descriptor, is introduced in Chapter 5. You learn about its two main functions: defining a component in XML as an alternative to annotations and assigning initial property values, either to control the behavior of a component or to build object prototypes. Although the metadata in this file is XML, Seam leverages namespaces to make the configuration type-safe. You even learn to develop your own namespace. Tucked away at the end of the chapter is an introduction to Seam’s simple, yet powerful, approach to managing message bundles.

Chapter 6 is paramount because it presents Seam’s most compelling and progressive feature, bijection. The key benefit bijection provides is to allow component instances in different scopes to safely collaborate without risk of scope impedance or concurrency violations. The other theme in this chapter is how Seam initializes objects on demand.

Chapter 7 covers Seam’s conversation, another vital feature. Java-based web applications have always lacked a scope that correlates with the user’s activity. You discover that the conversation fits this need, overcomes the shortcomings of the HTTP session, and provides a way for the user to manage parallel activities. The most important use of the conversation is to manage the persistence context.

To appreciate how Seam improves Java persistence, you have to learn what it is. Chapter 8 gives you an introductory view of Java persistence and points you to valuable resources on the topic; explains how Java persistence is managed in a pure Java EE environment; and helps you distinguish between Hibernate and JPA.

Chapter 9 presents Java persistence under the stewardship of Seam and demonstrates how Seam gets persistence right, where Java EE falls short. You learn that the conversation-scoped persistence context frees you from lazy initialization errors and dirty merge operations. You also learn that Seam blankets the request in a series of transactions, extending the guarantees they provide to all operations in a request. The chapter concludes by examining the most important feature of a multiuser web application: the application transaction, which makes persistence operations in a conversation atomic.

Chapter 10 is round two of developing a CRUD application—only this time, you do everything yourself. Well, not everything. You learn how to leverage the classes in the Seam Application Framework to handle most of the boilerplate code, so all you have to do is design and customize the user interface. After reading Chapter 2 and Chapter 10, you should be able to do CRUD in your sleep.

An application wouldn’t be much use without security. In three strokes, Chapter 11 gets you authenticating users and then proceeds to teach you how to implement basic role-based and contextual rule-based authorization to protect your application in powerful ways.

One of the things Seam does well is make other technologies look good. In Chapter 12, you learn how to add Ajax to your application using RichFaces or ICEfaces components without touching a line of JavaScript. Seam manages state to ensure these Ajax interactions don’t bog down the server resources. You also learn to enhance the capabilities of JavaScript by giving it direct access to server-side components and learn to integrate Seam with a rich user interface technology such as GWT.

Chapter 13 lets you escape the humdrum of HTML by teaching you to create a wide variety of content types, such as PDFs, emails, charts, graphics, and binary documents. You also learn to style your application and give the user control over the user interface.

I had so much to talk about that the last two chapters wouldn’t fit in the book. On this book’s website (www.manning.com/SeaminAction), you can check out Seam’s business process management solution in Chapter 14 and Seam’s Spring integration in Chapter 15.

Appendix A shows you how to set up Seam and the supporting environment and prepares you to follow along with the source code for this book.

Who should read this book?

Seam in Action was described by one reviewer as “written by an expert for experts.” If you’ve picked up this book hoping it has the breadth of knowledge you seek, that quote should satisfy you. A second reviewer claimed that “experienced Seam developers are likely to get something out of reading the book.” Another stated that “even if you are already an expert in the underlying technologies, you will not be disappointed.” If you want to master Seam, it’s well worth having this book in your backpack.

Where does that leave the rest of you, who are just getting started with Seam? You won’t be disappointed either. If you’re a Seam newbie or a manager, you’ll get plenty of value out of just the first two chapters. If you want to go further, you have to ask yourself if you’re committed to learning about this technology and if you’re willing to put some effort into it. Are you ready to become an expert? If not, it might be best for you to start with the Seam reference documentation or perhaps an introductory book. Chances are, you’ll be back when you’re ready to know all the details about how Seam works.

If you’re still with me, be aware that you need some prior experience before you take on this book. I’ve been able to go into detail in the book because I’ve left out introductory material that’s readily available elsewhere. At the very least, I expect that you have experience developing with Java, using the Java Servlet API, and deploying to application servers or servlet containers. I move quickly through JSF and ORM technologies, assuming that you’ve at least read about them. You should also have some awareness of method interceptors and how they work, although this knowledge can be inferred from the text. Finally, if you’re interested in the parts of the book that cover the EJB 3 integration or Spring integration, you need some prior experience with these technologies. That sounds like a lot of prerequisites, but if you’re dedicated, you can pick up this information from the book and the resources I recommend as you read.

If you’re worried about the requirement to understand JSF, the next section provides a brief introduction that should get you by. I also suggest a couple of additional resources if you feel you need more explanation. Honestly, though, basic JSF is straightforward, and Seam hides a lot of complexity beyond that point.

What you need to know about JSF to use Seam

JSF is a component-oriented user interface (UI) framework as opposed to an action-based framework like Struts. Struts requires that you write a custom action handler that processes the request and then forwards control to a JSP page, which renders the HTML response. JSF, on the other hand, resolves a view template—typically a JSP page—automatically from a request and transfers control directly to it. The lack of a front controller may appear to be a step backward. The enhancement comes in the way the view template is processed.

JSF reads the view template, which contains custom JSP or Facelets tags, and constructs a UI component tree, effectively deferring the rendering process. The UI component tree is a hierarchical graph of Java objects that represents the structure of the page. Rendering is only a secondary concern and occurs when the component tree is “encoded” to the client (that is, the browser). The renderer attached to each component produces the markup.

The main concern of the UI component tree is to act as a server-side representation of the view and listen for events that occur in the UI. There is a one-to-one mapping between the elements in the component tree and the elements on the page (with the exception of literal HTML). For instance, if the page contains a form with inputs and buttons, a corresponding form and nested input and button components exist in the UI component tree. Because the processing of the view template is separate from the encoding of the UI component tree, you can build the component tree using an alternate view technology, such as Facelets or pure Java. The component tree can also produce markup other than HTML.

The design of JSF goes beyond separating the view definition and view rendering with an intermediary object graph. JSF uses the component tree to capture events and allow programmatic, server-side manipulation of the view. In this regard, it’s similar to Swing, except that it operates in the context of the web environment. Any event performed by the user results in an HTTP request. During this request, or postback, the component tree is “restored” from its previous state. The events are processed, and the component tree is once again encoded to the client (the HTML response).

A simple example of the event mechanism is when the user clicks a button—a UICommand component—in a JSF form. As a result, the method bound to the action of the button is executed. You don’t have to worry about how the request is handled or how this mapping is prepared. If the form has inputs—UIInput components—the values in those inputs are assigned to the JavaBean properties to which they’re bound. The properties are then available to the action method when it executes. The objects that are bound to UI components are called managed beans. As you learn later, JSF does the managing.

How is a managed bean bound to a UI component? This binding is done using expression language (EL) notation, also found in JSP. There are both value- and method-binding expressions, although the latter are unique to JSF. JSF can use a value expression to capture a property value, in addition to outputting it, unlike in JSP. A method expression is used to bind a method to a UI component so that the method is invoked when the component is activated.

In the button example, a method on a managed bean might be bound to the action of the button through the expression #{beanName.methodName}. This expression resolves to the methodName() method on an instance of a JSF managed bean named beanName. Managed beans are defined in the JSF descriptor, faces-config.xml, using the <managed-bean> element. JSF automatically creates instances of these managed beans as needed.

Value expressions appear identical to method expressions, although they have a vastly different purpose. The value of an input component might be bound to a property on a managed bean using the expression #{beanName.propertyName}. JSF reads the value from the JavaBean getter method, getPropertyName(), when the page is rendered and writes the new value captured in the input to the setter method, setPropertyName(), after the button is clicked. Again, you don’t have to worry about reading request values from the HttpServletRequest object. The assignment happens automatically, and you can focus on implementing the business logic.

The EL is an important part of JSF and Seam, and you should be sure to understand it. Two resources I recommend are the article “Unified Expression Language for JSP and JSF,” published on java.net,[1] and the FAQs about the EL on seamframework.org.[2]



The example just presented appears simple enough, but what goes on during each JSF request, especially the postback, is quite a bit more sophisticated. Each request activates the JSF life cycle, which consists of six phases:

  1. Restore View
  2. Apply Request Values
  3. Process Validations (and conversions)
  4. Update Model Values
  5. Invoke Application
  6. Render Response

If the request is a postback, the UI component tree is restored during the Restore View phase. If this is an initial request, meaning the URL was requested from the browser’s location bar or a regular link, the life cycle skips directly to the Render Response phase.

A postback continues through the life cycle. In the three phases that follow Restore View, the form values are captured, converted, validated, and assigned to the JavaBean properties on the managed beans to which they are bound. Validations and conversions get assigned to an input component either as nested tags or correlated with the property’s type in the JSF descriptor.

The Invoke Application phase is where the action methods are executed. There can be at most one primary action and any number of secondary action listeners. The difference between the two types is that only the primary action can trigger a navigation rule. The navigation rules, also defined in the JSF descriptor, dictate the next view to render and are consulted once the Invoke Application phase completes.

Finally, in the Render Response phase, the UI component tree is built from the view template and subsequently encoded to HTML (or alternate output) and sent to the browser (or client).

That’s all there is to JSF. If you’re a newcomer to the framework, this brief explanation may leave you wanting. In that case, I’ll point you to several excellent resources on JSF that should get you up to speed. If you read nothing else, check out the JSF for nonbelievers series[3] on IBM developerWorks. While you’re there, also check out the article titled “Facelets fits JSF like a glove”[4] to learn about Facelets, the alternate view technology used in Seam applications. If you’re willing to invest in your JSF knowledge, you should pick up a copy of either JavaServer Faces in Action (Manning, 2004) or Pro JSF and Ajax (Apress, 2006). When reading these resources, keep in mind that you’re studying JSF to learn how to use Seam, not necessarily to buy into JSF by itself. In Chapter 3, you learn about the many enhancements Seam brings to JSF, a combination that is sure to please.



Next, because this book makes numerous references to golf, I want to give you some background to help you understand it as well.

The game of golf

The objective of golf is simple. You must get your ball into a hole in the ground using the fewest strokes possible, beginning from an area paired with that hole known as a tee box— or tee for short. A regulation golf course has 18 such holes. Each hole has a par, which is a guideline for how many strokes you should expect to take to get the ball into the hole; this number is significant in calculating your score.

The term hole refers to both the hole in the ground and its pairing with a tee box. A hole has a fixed number of tee boxes, each identified by a color. The tee boxes are set various distances from the hole and represent different experience levels, to make the game more challenging for those who are better at it. You pick one color and start from the designated area for that color on each hole. Those starting points are known as your tee set. In a golf round, you play each hole in sequence for a given tee set.

To advance the ball, you use a set of golf clubs. Each golf club consists of a shaft and a head. The angle of the head determines the loft of the ball when you hit it. The lower the loft, the further the ball is supposed to go (realizing this difference requires some skill). To hit the ball, you swing the club much like you would a baseball bat, but don’t tell the golf pro I said that! You use a special club called a putter to advance the ball on the green—the area that surrounds the hole. When using the putter, you tap the ball rather than swing at it. Each time you make contact with the ball, regardless of which club you use, it counts as one stroke.

When you start each hole, you’re permitted to elevate your ball using a golf tee. The first shot on a hole is the only time you’re allowed to use this aid. The tee is intended to accommodate the swing of a driver, the club in your bag with the lowest loft. Once you take your first stroke on a given hole, you advance the ball using a club until the ball lies at rest in the hole. You then pick up your ball and walk—or ride—to the next tee. At the end of the round, you add up all your strokes to calculate your raw score (I won’t get into the concept of a handicap, but just know that it is used to weight your score.) The lower that number, the better you played.

I chose golf as the topic of the example application because, like programming, it’s challenging. In golf, you’re only as good as your next round. Sounds a lot like the programming world, doesn’t it? As soon as we master a technology, there’s one right behind it to learn. Fortunately, lots of books are available to help us keep on top of our game.

Code conventions

The book provides copious examples, which include all the Seam application artifacts: Java code, XML-based descriptors, Facelets templates, and Java property files. Source code in listings or in text is in a fixed-width font like this to separate it from ordinary text. If there is part of the example I want to draw your attention to, it will be emphasized using bolded code font. Additionally, Java method names, Java class names, Seam component names and context variable names, event names, request parameter names, Java keywords, object properties, EL expressions, Java 5 annotations and enum constants, XML elements and attributes, and commands in text are also presented using fixed-width font. When an annotation appears in the text, the @ symbol is treated as silent.

Java, XHTML, and XML can all be verbose. In many cases, the original source code (available online) has been reformatted; I’ve added line breaks and reworked indentation to accommodate the available page space in the book. In some cases, even this was not enough, and the listings include line-continuation markers ().

I apply several other space optimizations. Comments in the source code have been omitted from the listings, and the code is instead described in the text. Class imports in Java classes also tend to take up a lot of space, so I omit those in cases when the code editor can easily resolve them for you. The complete set of imports can be found in the source code. When an implementation of a method isn’t important or remains unchanged from a previous listing, you will see { ... }, which is a code fold. Often, I place Java 5 annotations inline with the properties or methods to which they apply to conserve space. Personally, I prefer to use a newline after each Java 5 annotation in my own code.

Code annotations accompany some of the source code listings, highlighting important concepts. In some cases, numbered bullets link to explanations that follow the listing.

The location of individual applications will be referred to throughout the book using a variable notion. For instance, the JBoss AS directory is tokenized as ${jboss.home}.

Source code downloads

Seam is an open source project released under the Lesser GNU Public License (LGPL). Directions for downloading the Seam distribution, which includes both the source and binaries, are available from the Seam community site, http://seamframework.org/Download/SeamDownloads.

The source code for the Open 18 examples in this book is available from http://code.google.com/p/seaminaction and released under the LGPL. Because Seam is constantly evolving, I decided to make the source code available as an open source project so that I can keep the code up to date for readers as needed. You can also download the code for the examples in the book from the publisher’s website, http://www.manning.com/SeaminAction. Details about how to use the source code can be found in the README.txt file at the root of the source code and also on the project wiki.

Organizing the software

To help you keep the software in order so that you can follow along with the source code examples, I recommend a directory structure that I adhere to throughout the book. But it’s just a recommendation. Only you have a say in where your files are placed, and these conventions are by no means a prerequisite to using Seam.

The Directory you Call “Home”

Your home directory is where your personal files live. The last path in the directory is typically the same as your username. The book uses the home directory of a fictional developer, whose username is twoputt, whenever an absolute path must be referenced. Table 1 shows the home directory for twoputt as it would appear on several different operating systems. Whenever you see twoputt’s home directory used in the book, replace it with your own home directory.

The home area on several operating systems

Operating system

Home area

Linux /home/twoputt
Mac OSX /Users/twoputt
Windows C:\Documents and Settings\twoputt

The terminal output included in the listings has been generated on a Linux system, but you can look beyond this detail because it makes no difference which operating system you use for developing Seam applications.

Structuring Your Home

Table 2 lists several folders, along with their purpose, that I like to set up when doing development. You’ll recognize these directories from the book’s source code.

Folders in the development area


What it contains

databases File-based databases and database schemas
lib JAR files not included with Seam, such as the H2 driver
opt Java applications, such as JBoss AS and Seam
projects Development projects

Appendix A shows you how to install the software you need to use the examples in this book and Seam, with references to this structure.

About the author

DAN ALLEN is an independent software consultant, author, and open source advocate. After graduating from Cornell University with a degree in materials science and engineering in 2000, Dan became captivated by the world of free and open source software, which is how he got his start in software development. He soon discovered the combination of Linux and the Java EE platform to be the ideal blend on which to build his professional career. In his search for a robust web framework, Dan discovered Seam, which was quickly granted this most coveted spot in his development toolbox. Excited about Seam, Dan decided to share his thoughts with the world. This project is a (rather extensive) continuation of his three-part series on Seam published by IBM developerWorks. Dan continues to write articles on Seam and related technologies. Dan is a member of the Seam project, an active participant in the Seam community, and a Java blogger. You can keep up with Dan’s development experiences by subscribing to his blog at http://mojavelinux.com.

Author Online

Purchase of Seam in Action includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum and subscribe to it, point your web browser to http://www.manning.com/SeaminAction. This page provides information on how to get on the forum once you are registered, what kind 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 meaningful dialogue among individual readers and between readers and the authors can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the AO remains voluntary (and unpaid). We suggest you try asking the author some challenging questions, lest his interest stray! Since authors are busy people, like most people in the technology field, there is a chance your question will not be answered as quickly as you would like. In that case, you are encouraged to try your question on the Seam community website, http://seamframework.org, where you will find a much larger pool of people reading and answering Seam-related posts.

The Author Online forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.