Seam - Contextual Components

A Framework for Java EE 5

Copyright © 2007 by Red Hat, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, V1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/).

Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.

Distribution of the work or derivative of the work in any standard (paper) book form for commercial purposes is prohibited unless prior permission is obtained from the copyright holder.

Red Hat and the Red Hat "Shadow Man" logo are registered trademarks of Red Hat, Inc. in the United States and other countries.

All other trademarks referenced herein are the property of their respective owners.

The GPG fingerprint of the security@redhat.com key is:

CA 20 86 86 2B D6 9D FC 65 F6 EC C4 21 91 80 CD DB 42 A6 0E

1801 Varsity Drive

RaleighNC 27606-2072

USA

Phone: +1 919 754 3700

Phone: 888 733 4281

Fax: +1 919 754 3701

PO Box 13588

Research Triangle ParkNC 27709

USA

Sep, 2007

Abstract

This book is a Reference Guide for Seam


Introduction to JBoss Seam
1. Seam Tutorial
1.1. Try the examples
1.1.1. Running the examples on JBoss AS
1.1.2. Running the examples on Tomcat
1.1.3. Running the example tests
1.2. Your first Seam application: the registration example
1.2.1. Understanding the code
1.2.2. How it works
1.3. Clickable lists in Seam: the messages example
1.3.1. Understanding the code
1.3.2. How it works
1.4. Seam and jBPM: the todo list example
1.4.1. Understanding the code
1.4.2. How it works
1.5. Seam pageflow: the numberguess example
1.5.1. Understanding the code
1.5.2. How it works
1.6. A complete Seam application: the Hotel Booking example
1.6.1. Introduction
1.6.2. Overview of the booking example
1.6.3. Understanding Seam conversations
1.6.4. The Seam UI control library
1.6.5. The Seam Debug Page
1.7. A complete application featuring Seam and jBPM: the DVD Store example
1.8. A complete application featuring Seam workspace management: the Issue Tracker example
1.9. An example of Seam with Hibernate: the Hibernate Booking example
1.10. A RESTful Seam application: the Blog example
1.10.1. Using "pull"-style MVC
1.10.2. Bookmarkable search results page
1.10.3. Using "push"-style MVC in a RESTful application
2. The contextual component model
2.1. Seam contexts
2.1.1. Stateless context
2.1.2. Event context
2.1.3. Page context
2.1.4. Conversation context
2.1.5. Session context
2.1.6. Business process context
2.1.7. Application context
2.1.8. Context variables
2.1.9. Context search priority
2.1.10. Concurrency model
2.2. Seam components
2.2.1. Stateless session beans
2.2.2. Stateful session beans
2.2.3. Entity beans
2.2.4. JavaBeans
2.2.5. Message-driven beans
2.2.6. Interception
2.2.7. Component names
2.2.8. Defining the component scope
2.2.9. Components with multiple roles
2.2.10. Built-in components
2.3. Bijection
2.4. Lifecycle methods
2.5. Conditional installation
2.6. Logging
2.7. The Mutable interface and @ReadOnly
2.8. Factory and manager components
3. Configuring Seam components
3.1. Configuring components via property settings
3.2. Configuring components via components.xml
3.3. Fine-grained configuration files
3.4. Configurable property types
3.5. Using XML Namespaces
4. Events, interceptors and exception handling
4.1. Seam events
4.1.1. Page actions
4.1.2. Component-driven events
4.1.3. Contextual events
4.2. Seam interceptors
4.3. Managing exceptions
4.3.1. Exceptions and transactions
4.3.2. Enabling Seam exception handling
4.3.3. Using annotations for exception handling
4.3.4. Using XML for exception handling
5. Conversations and workspace management
5.1. Seam's conversation model
5.2. Nested conversations
5.3. Starting conversations with GET requests
5.4. Using <s:link> and <s:button>
5.5. Success messages
5.6. Using an "explicit" conversation id
5.7. Workspace management
5.7.1. Workspace management and JSF navigation
5.7.2. Workspace management and jPDL pageflow
5.7.3. The conversation switcher
5.7.4. The conversation list
5.7.5. Breadcrumbs
5.8. Conversational components and JSF component bindings
6. Pageflows and business processes
6.1. Pageflow in Seam
6.1.1. The two navigation models
6.1.2. Seam and the back button
6.2. Using jPDL pageflows
6.2.1. Installing pageflows
6.2.2. Starting pageflows
6.2.3. Page nodes and transitions
6.2.4. Controlling the flow
6.2.5. Ending the flow
6.3. Business process management in Seam
6.4. Using jPDL business process definitions
6.4.1. Installing process definitions
6.4.2. Initializing actor ids
6.4.3. Initiating a business process
6.4.4. Task assignment
6.4.5. Task lists
6.4.6. Performing a task
7. Seam and Object/Relational Mapping
7.1. Introduction
7.2. Seam managed transactions
7.2.1. Enabling Seam-managed transactions
7.3. Seam-managed persistence contexts
7.3.1. Using a Seam-managed persistence context with JPA
7.3.2. Using a Seam-managed Hibernate session
7.3.3. Seam-managed persistence contexts and atomic conversations
7.4. Using the JPA "delegate"
7.5. Using EL in EJB-QL/HQL
7.6. Using Hibernate filters
8. JSF form validation in Seam
9. The Seam Application Framework
9.1. Introduction
9.2. Home objects
9.3. Query objects
9.4. Controller objects
10. Seam and JBoss Rules
10.1. Installing rules
10.2. Using rules from a Seam component
10.3. Using rules from a jBPM process definition
11. Security
11.1. Overview
11.1.1. Which mode is right for my application?
11.2. Requirements
11.3. Authentication
11.3.1. Configuration
11.3.2. Writing an authentication method
11.3.3. Writing a login form
11.3.4. Simplified Configuration - Summary
11.3.5. Handling Security Exceptions
11.3.6. Login Redirection
11.3.7. Advanced Authentication Features
11.4. Error Messages
11.5. Authorization
11.5.1. Core concepts
11.5.2. Securing components
11.5.3. Security in the user interface
11.5.4. Securing pages
11.5.5. Securing Entities
11.6. Writing Security Rules
11.6.1. Permissions Overview
11.6.2. Configuring a rules file
11.6.3. Creating a security rules file
11.7. SSL Security
11.8. Implementing a Captcha Test
11.8.1. Configuring the Captcha Servlet
11.8.2. Adding a Captcha to a page
12. Internationalization and themes
12.1. Locales
12.2. Labels
12.2.1. Defining labels
12.2.2. Displaying labels
12.2.3. Faces messages
12.3. Timezones
12.4. Themes
12.5. Persisting locale and theme preferences via cookies
13. Seam Text
13.1. Basic fomatting
13.2. Entering code and text with special characters
13.3. Links
13.4. Entering HTML
14. iText PDF generation
14.1. Using PDF Support
14.2. Creating a document
14.2.1. p:document
14.3. Basic Text Elements
14.3.1. p:paragraph
14.3.2. p:text
14.3.3. p:font
14.3.4. p:newPage
14.3.5. p:image
14.3.6. p:anchor
14.4. Headers and Footers
14.4.1. p:header and p:footer
14.4.2. p:pageNumber
14.5. Chapters and Sections
14.5.1. p:chapter and p:section
14.5.2. p:title
14.6. Lists
14.6.1. p:list
14.6.2. p:listItem
14.7. Tables
14.7.1. p:table
14.7.2. p:cell
14.8. Document Constants
14.8.1. Color Values
14.8.2. Alignment Values
14.9. Configuring iText
14.10. iText links
15. Email
15.1. Creating a message
15.1.1. Attachments
15.1.2. HTML/Text alternative part
15.1.3. Multiple recipients
15.1.4. Multiple messages
15.1.5. Templating
15.1.6. Internationalisation
15.1.7. Other Headers
15.2. Receiving emails
15.3. Configuration
15.3.1. mailSession
15.4. Tags
16. Asynchronicity and messaging
16.1. Asynchronicity
16.1.1. Asynchronous methods
16.1.2. Asynchronous events
16.2. Messaging in Seam
16.2.1. Configuration
16.2.2. Sending messages
16.2.3. Receiving messages using a message-driven bean
16.2.4. Receiving messages in the client
17. Caching
17.1. Using JBossCache in Seam
17.2. Page fragment caching
18. Remoting
18.1. Configuration
18.2. The "Seam" object
18.2.1. A Hello World example
18.2.2. Seam.Component
18.2.3. Seam.Remoting
18.3. Client Interfaces
18.4. The Context
18.4.1. Setting and reading the Conversation ID
18.5. Batch Requests
18.6. Working with Data types
18.6.1. Primitives / Basic Types
18.6.2. JavaBeans
18.6.3. Dates and Times
18.6.4. Enums
18.6.5. Collections
18.7. Debugging
18.8. The Loading Message
18.8.1. Changing the message
18.8.2. Hiding the loading message
18.8.3. A Custom Loading Indicator
18.9. Controlling what data is returned
18.9.1. Constraining normal fields
18.9.2. Constraining Maps and Collections
18.9.3. Constraining objects of a specific type
18.9.4. Combining Constraints
18.10. JMS Messaging
18.10.1. Configuration
18.10.2. Subscribing to a JMS Topic
18.10.3. Unsubscribing from a Topic
18.10.4. Tuning the Polling Process
19. Spring Framework integration
19.1. Injecting Seam components into Spring beans
19.2. Injecting Spring beans into Seam components
19.3. Making a Spring bean into a Seam component
19.4. Seam-scoped Spring beans
19.5. Spring Application Context as a Seam Component
20. Configuring Seam and packaging Seam applications
20.1. Basic Seam configuration
20.1.1. Integrating Seam with JSF and your servlet container
20.1.2. Seam Resource Servlet
20.1.3. Seam servlet filters
20.1.4. Integrating Seam with your EJB container
20.1.5. Using facelets
20.1.6. Don't forget!
20.2. Configuring Seam in Java EE 5
20.2.1. Packaging
20.3. Configuring Seam in Java SE, with the JBoss Embeddable EJB3 container
20.3.1. Installing the Embeddable EJB3 container
20.3.2. Configuring a datasource with the Embeddable EJB3 container
20.3.3. Packaging
20.4. Configuring Seam in J2EE
20.4.1. Boostrapping Hibernate in Seam
20.4.2. Boostrapping JPA in Seam
20.4.3. Packaging
20.5. Configuring Seam in Java SE, with the JBoss Microcontainer
20.5.1. Using Hibernate and the JBoss Microcontainer
20.5.2. Packaging
20.6. Configuring jBPM in Seam
20.6.1. Packaging
20.7. Configuring Seam in a Portal
20.8. Configuring SFSB and Session Timeouts in JBoss AS
21. Seam annotations
21.1. Annotations for component definition
21.2. Annotations for bijection
21.3. Annotations for component lifecycle methods
21.4. Annotations for context demarcation
21.5. Annotations for transaction demarcation
21.6. Annotations for exceptions
21.7. Annotations for validation
21.8. Annotations for Seam Remoting
21.9. Annotations for Seam interceptors
21.10. Annotations for asynchronicity
21.11. Annotations for use with JSF dataTable
21.12. Meta-annotations for databinding
21.13. Annotations for packaging
22. Built-in Seam components
22.1. Context injection components
22.2. Utility components
22.3. Components for internationalization and themes
22.4. Components for controlling conversations
22.5. jBPM-related components
22.6. Security-related components
22.7. JMS-related components
22.8. Mail-related components
22.9. Infrastructural components
22.10. Special components
23. Seam JSF controls
24. Expression language enhancements
24.1. Configuration
24.2. Usage
24.3. Limitations
24.3.1. Incompatibility with JSP 2.1
24.3.2. Calling a MethodExpression from Java code
25. Testing Seam applications
25.1. Unit testing Seam components
25.2. Integration testing Seam applications
25.2.1. Using mocks in integration tests
26. Seam tools
26.1. jBPM designer and viewer
26.1.1. Business process designer
26.1.2. Pageflow viewer
26.2. CRUD-application generator
26.2.1. Creating a Hibernate configuration file
26.2.2. Creating a Hibernate Console configuration
26.2.3. Reverse engineering and code generation
Index

Introduction to JBoss Seam

Seam is an application framework for Java EE 5. It is inspired by the following principles:

Integrate JSF with EJB 3.0

JSF and EJB 3.0 are two of the best new features of Java EE 5. EJB3 is a brand new component model for server side business and persistence logic. Meanwhile, JSF is a great component model for the presentation tier. Unfortunately, neither component model is able to solve all problems in computing by itself. Indeed, JSF and EJB3 work best used together. But the Java EE 5 specification provides no standard way to integrate the two component models. Fortunately, the creators of both models foresaw this situation and provided standard extension points to allow extension and integration of other solutions.

Seam unifies the component models of JSF and EJB3, eliminating glue code, and letting the developer think about the business problem.

Integrated AJAX

Seam supports two open source JSF-based AJAX solutions: ICEfaces and Ajax4JSF. These solutions let you add AJAX capability to your user interface without the need to write any JavaScript code.

Seam also provides a built-in JavaScript remoting layer for EJB3 components. AJAX clients can easily call server-side components and subscribe to JMS topics, without the need for an intermediate action layer.

Neither of these approaches would work well, were it not for Seam's built-in concurrency and state management, which ensures that many concurrent fine-grained, asynchronous AJAX requests are handled safely and efficiently on the server side.

Integrate Business Process as a First Class Construct

Optionally, Seam integrates transparent business process management via jBPM. You won't believe how easy it is to implement complex workflows using jBPM and Seam.

Seam even allows definition of presentation tier conversation flow by the same means.

JSF provides an incredibly rich event model for the presentation tier. Seam enhances this model by exposing jBPM's business process related events via exactly the same event handling mechanism, providing a uniform event model for Seam's uniform component model.

One Kind of "Stuff"

Seam provides a uniform component model. A Seam component may be stateful, with the state associated to any one of a number of contexts, ranging from the long-running business process to a single web request.

There is no distinction between presentation tier components and business logic components in Seam. It is possible to write Seam applications where "everything" is an EJB. This may come as a surprise if you are used to thinking of EJBs as coarse-grained, heavyweight objects that are a pain in the backside to create! However, EJB 3.0 completely changes the nature of EJB from the point of view of the developer. An EJB is a fine-grained object - nothing more complex than an annotated JavaBean. Seam even encourages you to use session beans as JSF action listeners!

Unlike plain Java EE or J2EE components, Seam components may simultaneously access state associated with the web request and state held in transactional resources (without the need to propagate web request state manually via method parameters). You might object that the application layering imposed upon you by the old J2EE platform was a Good Thing. Well, nothing stops you creating an equivalent layered architecture using Seam - the difference is that you get to architect your own application and decide what the layers are and how they work together.

Declarative State Management

We are all used to the concept of declarative transaction management and J2EE declarative security from EJB 2.x. EJB 3.0 even introduces declarative persistence context management. These are three examples of a broader problem of managing state that is associated with a particular context, while ensuring that all needed cleanup occurs when the context ends. Seam takes the concept of declarative state management much further and applies it to application state. Traditionally, J2EE applications almost always implement state management manually, by getting and setting servlet session and request attributes. This approach to state management is the source of many bugs and memory leaks when applications fail to clean up session attributes, or when session data associated with different workflows collides in a multi-window application. Seam has the potential to almost entirely eliminate this class of bugs.

Declarative application state management is made possible by the richness of the context model defined by Seam. Seam extends the context model defined by the servlet spec—request, session, application—with two new contexts—conversation and business process—that are more meaningful from the point of view of the business logic.

Bijection

The notion of Inversion of Control or dependency injection exists in both JSF and EJB3, as well as in numerous so-called "lighweight containers". Most of these containers emphasize injection of components that implement stateless services. Even when injection of stateful components is supported (such as in JSF), it is virtually useless for handling application state because the scope of the stateful component cannot be defined with sufficient flexibility.

Bijection differs from IoC in that it is dynamic, contextual, and bidirectional. You can think of it as a mechanism for aliasing contextual variables (names in the various contexts bound to the current thread) to attributes of the component. Bijection allows auto-assembly of stateful components by the container. It even allows a component to safely and easily manipulate the value of a context variable, just by assigning to an attribute of the component.

Workspace Management

Optionally, Seam applications may take advantage of workspace management, allowing users to freely switch between different conversations (workspaces) in a single browser window. Seam provides not only correct multi-window operation, but also multi-window-like operation in a single window!

Annotated POJOs Everywhere

EJB 3.0 embraces annotations and "configuration by exception" as the easiest way to provide information to the container in a declarative form. Unfortunately, JSF is still heavily dependent on verbose XML configuration files. Seam extends the annotations provided by EJB 3.0 with a set of annotations for declarative state management and declarative context demarcation. This lets you eliminate the noisy JSF managed bean declarations and reduce the required XML to just that information which truly belongs in XML (the JSF navigation rules).

Testability as a Core Feature

Seam components, being POJOs, are by nature unit testable. But for complex applications, unit testing alone is insufficient. Integration testing has traditionally been a messy and difficult task for Java web applications. Therefore, Seam provides for testability of Seam applications as a core feature of the framework. You can easily write JUnit or TestNG tests that reproduce a whole interaction with a user, exercising all components of the system apart from the view (the JSP or Facelets page). You can run these tests directly inside your IDE, where Seam will automatically deploy EJB components into the JBoss Embeddable EJB3 container.

Get started now!

Seam works in any application server that supports EJB 3.0. You can even use Seam in a servlet container like Tomcat, or in any J2EE application server, by leveraging the new JBoss Embeddable EJB3 container.

However, we realize that not everyone is ready to make the switch to EJB 3.0. So, in the interim, you can use Seam as a framework for applications that use JSF for presentation, Hibernate (or plain JDBC) for persistence and JavaBeans for application logic. Then, when you're ready to make the switch to EJB 3.0, migration will be straightforward.

It turns out that the combination of Seam, JSF and EJB3 is the simplest way to write a complex web application in Java. You won't believe how little code is required!

Chapter 1. Seam Tutorial

1.1. Try the examples

In this tutorial, we'll assume that you are using JBoss AS 4.2 with Seam, as in the case of JBoss Enterprise Application Platform.

The directory structure of each example in Seam follows this pattern:

  • Web pages, images and stylesheets may be found in examples/registration/view

  • Resources such as deployment descriptors and data import scripts may be found in examples/registration/resources

  • Java source code may be found in examples/registration/src

  • The Ant build script is examples/registration/build.xml

1.1.1. Running the examples on JBoss AS

First, make sure you have Ant correctly installed, with $ANT_HOME and $JAVA_HOME set correctly. Next, make sure you set the location of your JBoss AS installation in the build.properties file in the root folder of your Seam installation. If you haven't already done so, start JBoss AS now by typing bin/run.sh or bin/run.bat in the root directory of your JBoss installation.

By default the examples will deploy to the default configuration of the server. These examples should be deployed to the production configuration if they are to be used with JBoss Enterprise Application Platform 4.2, and the example build.xml file should be modified to reflect this before building and deploying. Two lines should be changed in this file:

 <property name="deploy.dir"           value="${jboss.home}/server/production/deploy"/>
   <property name="webroot.dir"         
	value="${deploy.dir}/jboss-web.deployer/ROOT.war"/>

Now, build and deploy the example by typing ant deploy in the examples/registration directory.

Try it out by accessing http://localhost:8080/seam-registration/ with your web browser.

1.1.2. Running the examples on Tomcat

First, make sure you have Ant correctly installed, with $ANT_HOME and $JAVA_HOME set correctly. Next, make sure you set the location of your Tomcat installation in the build.properties file in the root folder of your Seam installation.

Now, build and deploy the example by typing ant deploy.tomcat in the examples/registration directory.

Finally, start Tomcat.

Try it out by accessing http://localhost:8080/jboss-seam-registration/ with your web browser.

When you deploy the example to Tomcat, any EJB3 components will run inside the JBoss Embeddable EJB3 container, a complete standalone EJB3 container environment.

1.1.3. Running the example tests

Most of the examples come with a suite of TestNG integration tests. The easiest way to run the tests is to run ant testexample inside the examples/registration directory. It is also possible to run the tests inside your IDE using the TestNG plugin.

1.2. Your first Seam application: the registration example

The registration example is a fairly trivial application that lets a new user store his username, real name and password in the database. The example isn't intended to show off all of the cool functionality of Seam. However, it demonstrates the use of an EJB3 session bean as a JSF action listener, and basic configuration of Seam.

We'll go slowly, since we realize you might not yet be familiar with EJB 3.0.

The start page displays a very basic form with three input fields. Try filling them in and then submitting the form. This will save a user object in the database.

1.2.1. Understanding the code

The example is implemented with two JSP pages, one entity bean and one stateless session bean.

Let's take a look at the code, starting from the "bottom".

1.2.1.1. The entity bean: User.java

We need an EJB entity bean for user data. This class defines persistence and validation declaratively, via annotations. It also needs some extra annotations that define the class as a Seam component.

@Entity
@Name("user")
@Scope(SESSION)
@Table(name="users")
public class User implements Serializable
{
   private static final long serialVersionUID = 1881413500711441951L;
   
   private String username;
   private String password;
   private String name;
   
   public User(String name, String password, String username)
   {
      this.name = name;
      this.password = password;
      this.username = username;
   }
   
   public User() {}
   
   @NotNull @Length(min=5, max=15)
   public String getPassword()
   {
      return password;
   }

   public void setPassword(String password)
   {
      this.password = password;
   }
   
   @NotNull
   public String getName()
   {
      return name;
   }

   public void setName(String name)
   {
      this.name = name;
   }
   
   @Id @NotNull @Length(min=5, max=15)
   public String getUsername()
   {
      return username;
   }

   public void setUsername(String username)
   {
      this.username = username;
   }

}
1

The EJB3 standard @Entity annotation indicates that the User class is an entity bean.

2

A Seam component needs a component name specified by the @Name annotation. This name must be unique within the Seam application. When JSF asks Seam to resolve a context variable with a name that is the same as a Seam component name, and the context variable is currently undefined (null), Seam will instantiate that component, and bind the new instance to the context variable. In this case, Seam will instantiate a User the first time JSF encounters a variable named user.

3

Whenever Seam instantiates a component, it binds the new instance to a context variable in the component's default context. The default context is specified using the @Scope annotation. The User bean is a session scoped component.

4

The EJB standard @Table annotation indicates that the User class is mapped to the users table.

5

name, password and username are the persistent attributes of the entity bean. All of our persistent attributes define accessor methods. These are needed when this component is used by JSF in the render response and update model values phases.

6

An empty constructor is both required by both the EJB specification and by Seam.

7

The @NotNull and @Length annotations are part of the Hibernate Validator framework. Seam integrates Hibernate Validator and lets you use it for data validation (even if you are not using Hibernate for persistence).

8

The EJB standard @Id annotation indicates the primary key attribute of the entity bean.

The most important things to notice in this example are the @Name and @Scope annotations. These annotations establish that this class is a Seam component.

We'll see below that the properties of our User class are bound to directly to JSF components and are populated by JSF during the update model values phase. We don't need any tedious glue code to copy data back and forth between the JSP pages and the entity bean domain model.

However, entity beans shouldn't do transaction management or database access. So we can't use this component as a JSF action listener. For that we need a session bean.

Example 1.1. 



1.2.1.2. The stateless session bean class: RegisterAction.java

Most Seam application use session beans as JSF action listeners (you can use JavaBeans instead if you like).

We have exactly one JSF action in our application, and one session bean method attached to it. In this case, we'll use a stateless session bean, since all the state associated with our action is held by the User bean.

This is the only really interesting code in the example!

@Stateless
@Name("register")
public class RegisterAction implements Register
{

   @In
   private User user;
   
   @PersistenceContext
   private EntityManager em;
   
   @Logger
   private Log log;
   
   public String register()
   {
      List existing = em.createQuery(
         "select username from User where username=#{user.username}")
         .getResultList();
         
      if (existing.size()==0)
      {
         em.persist(user);
         log.info("Registered new user #{user.username}");
         return "/registered.jsp";
      }
      else
      {
         FacesMessages.instance().add("User #{user.username} already exists");
         return null;
      }
   }

}
1

The EJB standard @Stateless annotation marks this class as stateless session bean.

2

The @In annotation marks an attribute of the bean as injected by Seam. In this case, the attribute is injected from a context variable named user (the instance variable name).

3

The EJB standard @PersistenceContext annotation is used to inject the EJB3 entity manager.

4

The Seam @Logger annotation is used to inject the component's Log instance.

5

The action listener method uses the standard EJB3 EntityManager API to interact with the database, and returns the JSF outcome. Note that, since this is a sesson bean, a transaction is automatically begun when the register() method is called, and committed when it completes.

6

Notice that Seam lets you use a JSF EL expression inside EJB-QL. Under the covers, this results in an ordinary JPA setParameter() call on the standard JPA Query object. Nice, huh?

7

The Log API lets us easily display templated log messages.

8

JSF action listener methods return a string-valued outcome that determines what page will be displayed next. A null outcome (or a void action listener method) redisplays the previous page. In plain JSF, it is normal to always use a JSF navigation rule to determine the JSF view id from the outcome. For complex application this indirection is useful and a good practice. However, for very simple examples like this one, Seam lets you use the JSF view id as the outcome, eliminating the requirement for a navigation rule. Note that when you use a view id as an outcome, Seam always performs a browser redirect.

9

Seam provides a number of built-in components to help solve common problems. The FacesMessages component makes it easy to display templated error or success messages. Built-in Seam components may be obtained by injection, or by calling an instance() method.

Note that we did not explicitly specify a @Scope this time. Each Seam component type has a default scope if not explicitly specified. For stateless session beans, the default scope is the stateless context. Actually, all stateless session beans belong in the stateless context.

Our session bean action listener performs the business and persistence logic for our mini-application. In more complex applications, we might need to layer the code and refactor persistence logic into a dedicated data access component. That's perfectly trivial to do. But notice that Seam does not force you into any particular strategy for application layering.

Furthermore, notice that our session bean has simultaneous access to context associated with the web request (the form values in the User object, for example), and state held in transactional resources (the EntityManager object). This is a break from traditional J2EE architectures. Again, if you are more comfortable with the traditional J2EE layering, you can certainly implement that in a Seam application. But for many applications, it's simply not very useful.

Example 1.2. 



1.2.1.3. The session bean local interface: Register.java

Naturally, our session bean needs a local interface.

@Local
public interface Register
{
   public String register();
}

Example 1.3. 



That's the end of the Java code. Now onto the deployment descriptors.

1.2.1.4. The Seam component deployment descriptor: components.xml

If you've used many Java frameworks before, you'll be used to having to declare all your component classes in some kind of XML file that gradually grows more and more unmanageable as your project matures. You'll be relieved to know that Seam does not require that application components be accompanied by XML. Most Seam applications require a very small amount of XML that does not grow very much as the project gets bigger.

Nevertheless, it is often useful to be able to provide for some external configuration of some components (particularly the components built in to Seam). You have a couple of options here, but the most flexible option is to provide this configuration in a file called components.xml, located in the WEB-INF directory. We'll use the components.xml file to tell Seam how to find our EJB components in JNDI:

<components xmlns="http://jboss.com/products/seam/components"
            xmlns:core="http://jboss.com/products/seam/core">
     <core:init jndi-pattern="@jndiPattern@"/>
</components>

Example 1.4. 



This code configures a property named jndiPattern of a built-in Seam component named org.jboss.seam.core.init.

1.2.1.5. The web deployment description: web.xml

The presentation layer for our mini-application will be deployed in a WAR. So we'll need a web deployment descriptor.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!- - Seam - ->

    <listener>
        <listener-class>org.jboss.seam.servlet.SeamListener</listener-class>
    </listener>
    
     <listener>
         <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>

    <context-param>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>client</param-value>
    </context-param>

    <context-param>
        <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
        <param-value>.jspx</param-value>
    </context-param>

        <servlet>
                <servlet-name>Faces Servlet</servlet-name>
                <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
                <load-on-startup>1</load-on-startup>
        </servlet>

        
        <servlet-mapping>
                <servlet-name>Faces Servlet</servlet-name>
                <url-pattern>*.seam</url-pattern>
        </servlet-mapping>

</web-app>

Example 1.5. 



This web.xml file configures Seam and Glassfish. The configuration you see here is pretty much identical in all Seam applications.

1.2.1.6. The JSF configration: faces-config.xml

All Seam applications use JSF views as the presentation layer. So we'll need faces-config.xml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE faces-config 
PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"
                            "http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
<faces-config>

    <!- - A phase listener is needed by all Seam applications - ->
    
    <lifecycle>
        <phase-listener>org.jboss.seam.jsf.SeamPhaseListener</phase-listener>
    </lifecycle>

</faces-config>

Example 1.6. 



The faces-config.xml file integrates Seam into JSF. Note that we don't need any JSF managed bean declarations! The managed beans are the Seam components. In Seam applications, the faces-config.xml is used much less often than in plain JSF.

In fact, once you have all the basic descriptors set up, the only XML you need to write as you add new functionality to a Seam application is the navigation rules, and possibly jBPM process definitions. Seam takes the view that process flow and configuration data are the only things that truly belong in XML.

In this simple example, we don't even need a navigation rule, since we decided to embed the view id in our action code.

1.2.1.7. The EJB deployment descriptor: ejb-jar.xml

The ejb-jar.xml file integrates Seam with EJB3, by attaching the SeamInterceptor to all session beans in the archive.

<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                           http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
         version="3.0">
         
   <interceptors>
     <interceptor>
       <interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class>
     </interceptor>
   </interceptors>
   
   <assembly-descriptor>
      <interceptor-binding>
         <ejb-name>*</ejb-name>
         <interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class>
      </interceptor-binding>
   </assembly-descriptor>
   
</ejb-jar>

1.2.1.8. The EJB persistence deployment descriptor: persistence.xml

The persistence.xml file tells the EJB persistence provider where to find the datasource, and contains some vendor-specific settings. In this case, enables automatic schema export at startup time.

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
                           http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" 
             version="1.0">
    <persistence-unit name="userDatabase">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <jta-data-source>java:/DefaultDS</jta-data-source>
      <properties>
         <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
      </properties>
    </persistence-unit>
</persistence>

1.2.1.9. The view: register.jsp and registered.jsp

The view pages for a Seam application could be implemented using any technology that supports JSF. In this example we use JSP, since it is familiar to most developers and since we have minimal requirements here anyway. (But if you take our advice, you'll use Facelets for your own applications.)

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://jboss.com/products/seam/taglib" prefix="s" %>
<html>
 <head>
  <title>Register New User</title>
 </head>
 <body>
  <f:view>
   <h:form>
     <table border="0">
       <s:validateAll>
         <tr>
           <td>Username</td>
           <td><h:inputText value="#{user.username}"/></td>
         </tr>
         <tr>
           <td>Real Name</td>
           <td><h:inputText value="#{user.name}"/></td>
         </tr>
         <tr>
           <td>Password</td>
           <td><h:inputSecret value="#{user.password}"/></td>
         </tr>
       </s:validateAll>
     </table>
     <h:messages/>
     <h:commandButton type="submit" value="Register" action="#{register.register}"/>
   </h:form>
  </f:view>
 </body>
</html>

Example 1.7. 



The only thing here that is specific to Seam is the <s:validateAll> tag. This JSF component tells JSF to validate all the contained input fields against the Hibernate Validator annotations specified on the entity bean.

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
 <head>
  <title>Successfully Registered New User</title>
 </head>
 <body>
  <f:view>
    Welcome, <h:outputText value="#{user.name}"/>, 
    you are successfully registered as <h:outputText value="#{user.username}"/>.
  </f:view>
 </body>
</html>

Example 1.8. 



This is a boring old JSP pages using standard JSF components. There is nothing specific to Seam here.

1.2.1.10. The EAR deployment descriptor: application.xml

Finally, since our application is deployed as an EAR, we need a deployment descriptor there, too.

<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/javaee" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                                   http://java.sun.com/xml/ns/javaee/application_5.xsd"
             version="5">
             
    <display-name>Seam Registration</display-name>

    <module>
        <web>
            <web-uri>jboss-seam-registration.war</web-uri>
            <context-root>/seam-registration</context-root>
        </web>
    </module>
    <module>
        <ejb>jboss-seam-registration.jar</ejb>
    </module>
    <module>
        <java>jboss-seam.jar</java>
    </module>
    <module>
        <java>el-ri.jar</java>
    </module>
    
</application>

Example 1.9. 



This deployment descriptor links modules in the enterprise archive and binds the web application to the context root /seam-registration.

1.2.2. How it works

When the form is submitted, JSF asks Seam to resolve the variable named user. Since there is no value already bound to that name (in any Seam context), Seam instantiates the user component, and returns the resulting User entity bean instance to JSF after storing it in the Seam session context.

The form input values are now validated against the Hibernate Validator constraints specified on the User entity. If the constraints are violated, JSF redisplays the page. Otherwise, JSF binds the form input values to properties of the User entity bean.

Next, JSF asks Seam to resolve the variable named register. Seam finds the RegisterAction stateless session bean in the stateless context and returns it. JSF invokes the register() action listener method.

Seam intercepts the method call and injects the User entity from the Seam session context, before continuing the invocation.

The register() method checks if a user with the entered username already exists. If so, an error message is queued with the FacesMessages component, and a null outcome is returned, causing a page redisplay. The FacesMessages component interpolates the JSF expression embedded in the message string and adds a JSF FacesMessage to the view.

If no user with that username exists, the "/registered.jsp" outcome triggers a browser redirect to the registered.jsp page. When JSF comes to render the page, it asks Seam to resolve the variable named user and uses property values of the returned User entity from Seam's session scope.

1.3. Clickable lists in Seam: the messages example

Clickable lists of database search results are such an important part of any online application that Seam provides special functionality on top of JSF to make it easier to query data using EJB-QL or HQL and display it as a clickable list using a JSF <h:dataTable>. The messages example demonstrates this functionality.

1.3.1. Understanding the code

The message list example has one entity bean, Message, one session bean, MessageListBean and one JSP.

1.3.1.1. The entity bean: Message.java

The Message entity defines the title, text, date and time of a message, and a flag indicating whether the message has been read:

@Entity
@Name("message")
@Scope(EVENT)
public class Message implements Serializable
{
   private Long id;
   private String title;
   private String text;
   private boolean read;
   private Date datetime;
   
   @Id @GeneratedValue
   public Long getId() {
      return id;
   }
   public void setId(Long id) {
      this.id = id;
   }
   
   @NotNull @Length(max=100)
   public String getTitle() {
      return title;
   }
   public void setTitle(String title) {
      this.title = title;
   }
   
   @NotNull @Lob
   public String getText() {
      return text;
   }
   public void setText(String text) {
      this.text = text;
   }
   
   @NotNull
   public boolean isRead() {
      return read;
   }
   public void setRead(boolean read) {
      this.read = read;
   }
   
   @NotNull 
   @Basic @Temporal(TemporalType.TIMESTAMP)
   public Date getDatetime() {
      return datetime;
   }
   public void setDatetime(Date datetime) {
      this.datetime = datetime;
   }
   
}

Example 1.10. 



1.3.1.2. The stateful session bean: MessageManagerBean.java

Just like in the previous example, we have a session bean, MessageManagerBean, which defines the action listener methods for the two buttons on our form. One of the buttons selects a message from the list, and displays that message. The other button deletes a message. So far, this is not so different to the previous example.

But MessageManagerBean is also responsible for fetching the list of messages the first time we navigate to the message list page. There are various ways the user could navigate to the page, and not all of them are preceded by a JSF action—the user might have bookmarked the page, for example. So the job of fetching the message list takes place in a Seam factory method, instead of in an action listener method.

We want to cache the list of messages in memory between server requests, so we will make this a stateful session bean.

@Stateful
@Scope(SESSION)
@Name("messageManager")
public class MessageManagerBean implements Serializable, MessageManager
{

   @DataModel
   private List<Message> messageList;
   
   @DataModelSelection
   @Out(required=false)
   private Message message;
   
   @PersistenceContext(type=EXTENDED)
   private EntityManager em;
   
   @Factory("messageList")
   public void findMessages()
   {
      messageList = em.createQuery("from Message msg order by msg.datetime desc").getResultList();
   }
   
   public void select()
   {
      message.setRead(true);
   }
   
   public void delete()
   {
      messageList.remove(message);
      em.remove(message);
      message=null;
   }
   
   @Remove @Destroy
   public void destroy() {}

}
1

The @DataModel annotation exposes an attibute of type java.util.List to the JSF page as an instance of javax.faces.model.DataModel. This allows us to use the list in a JSF <h:dataTable> with clickable links for each row. In this case, the DataModel is made available in a session context variable named messageList.

2

The @DataModelSelection annotation tells Seam to inject the List element that corresponded to the clicked link.

3

The @Out annotation then exposes the selected value directly to the page. So ever time a row of the clickable list is selected, the Message is injected to the attribute of the stateful bean, and the subsequently outjected to the event context variable named message.

4

This stateful bean has an EJB3 extended persistence context. The messages retrieved in the query remain in the managed state as long as the bean exists, so any subsequent method calls to the stateful bean can update them without needing to make any explicit call to the EntityManager.

5

The first time we navigate to the JSP page, there will be no value in the messageList context variable. The @Factory annotation tells Seam to create an instance of MessageManagerBean and invoke the findMessages() method to initialize the value. We call findMessages() a factory method for messages.

6

The select() action listener method marks the selected Message as read, and updates it in the database.

7

The delete() action listener method removes the selected Message from the database.

8

All stateful session bean Seam components must have a method marked @Remove @Destroy to ensure that Seam will remove the stateful bean when the Seam context ends, and clean up any server-side state.

Example 1.11. 



Note that this is a session-scoped Seam component. It is associated with the user login session, and all requests from a login session share the same instance of the component. (In Seam applications, we usually use session-scoped components sparingly.)

1.3.1.3. The session bean local interface: MessageManager.java

All session beans have a business interface, of course.

@Local
public interface MessageManager
{
   public void findMessages();
   public void select();
   public void delete();
   public void destroy();
}

From now on, we won't show local interfaces in our code examples.

Let's skip over components.xml, persistence.xml, web.xml, ejb-jar.xml, faces-config.xml and application.xml since they are much the same as the previous example, and go straight to the JSP.

1.3.1.4. The view: messages.jsp

The JSP page is a straightforward use of the JSF <h:dataTable> component. Again, nothing specific to Seam.

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
 <head>
  <title>Messages</title>
 </head>
 <body>
  <f:view>
   <h:form>
     <h2>Message List</h2>
     <h:outputText value="No messages to display" rendered="#{messageList.rowCount==0}"/>
     <h:dataTable var="msg" value="#{messageList}" rendered="#{messageList.rowCount>0}">
        <h:column>
           <f:facet name="header">
              <h:outputText value="Read"/>
           </f:facet>
           <h:selectBooleanCheckbox value="#{msg.read}" disabled="true"/>
        </h:column>
        <h:column>
           <f:facet name="header">
              <h:outputText value="Title"/>
           </f:facet>
           <h:commandLink value="#{msg.title}" action="#{messageManager.select}"/>
        </h:column>
        <h:column>
           <f:facet name="header">
              <h:outputText value="Date/Time"/>
           </f:facet>
           <h:outputText value="#{msg.datetime}">
              <f:convertDateTime type="both" dateStyle="medium" timeStyle="short"/>
           </h:outputText>
        </h:column>
        <h:column>
           <h:commandButton value="Delete" action="#{messageManager.delete}"/>
        </h:column>
     </h:dataTable>
     <h3><h:outputText value="#{message.title}"/></h3>
     <div><h:outputText value="#{message.text}"/></div>
   </h:form>
  </f:view>
 </body>
</html>

Example 1.12. 



1.3.2. How it works

The first time we navigate to the messages.jsp page, whether by a JSF postback (faces request) or a direct browser GET request (non-faces request), the page will try to resolve the messageList context variable. Since this context variable is not initialized, Seam will call the factory method findMessages(), which performs a query against the database and results in a DataModel being outjected. This DataModel provides the row data needed for rendering the <h:dataTable>.

When the user clicks the <h:commandLink>, JSF calls the select() action listener. Seam intercepts this call and injects the selected row data into the message attribute of the messageManager component. The action listener fires, marking the selected Message as read. At the end of the call, Seam outjects the selected Message to the context variable named message. Next, the EJB container commits the transaction, and the change to the Message is flushed to the database. Finally, the page is re-rendered, redisplaying the message list, and displaying the selected message below it.

If the user clicks the <h:commandButton>, JSF calls the delete() action listener. Seam intercepts this call and injects the selected row data into the message attribute of the messageList component. The action listener fires, removing the selected Message from the list, and also calling remove() on the EntityManager. At the end of the call, Seam refreshes the messageList context variable and clears the context variable named message. The EJB container commits the transaction, and deletes the Message from the database. Finally, the page is re-rendered, redisplaying the message list.

1.4. Seam and jBPM: the todo list example

jBPM provides sophisticated functionality for workflow and task management. To get a small taste of how jBPM integrates with Seam, we'll show you a simple "todo list" application. Since managing lists of tasks is such core functionality for jBPM, there is hardly any Java code at all in this example.

1.4.1. Understanding the code

The center of this example is the jBPM process definition. There are also two JSPs and two trivial JavaBeans (There was no reason to use session beans, since they do not access the database, or have any other transactional behavior). Let's start with the process definition:

<process-definition name="todo">
   
   <start-state name="start">
      <transition to="todo"/>
   </start-state>
   
   <task-node name="todo">
      <task name="todo" description="#{todoList.description}">
         <assignment actor-id="#{actor.id}"/>
      </task>
      <transition to="done"/>
   </task-node>
   
   <end-state name="done"/>
   
</process-definition>
1

The <start-state> node represents the logical start of the process. When the process starts, it immediately transitions to the todo node.

2

The <task-node> node represents a wait state, where business process execution pauses, waiting for one or more tasks to be performed.

3

The <task> element defines a task to be performed by a user. Since there is only one task defined on this node, when it is complete, execution resumes, and we transition to the end state. The task gets its description from a Seam component named todoList (one of the JavaBeans).

4

Tasks need to be assigned to a user or group of users when they are created. In this case, the task is assigned to the current user, which we get from a built-in Seam component named actor. Any Seam component may be used to perform task assignment.

5

The <end-state> node defines the logical end of the business process. When execution reaches this node, the process instance is destroyed.

Example 1.13. 



If we view this process definition using the process definition editor provided by JBossIDE, this is what it looks like:

This document defines our business process as a graph of nodes. This is the most trivial possible business process: there is one task to be performed, and when that task is complete, the business process ends.

The first JavaBean handles the login screen login.jsp. Its job is just to initialize the jBPM actor id using the actor component. (In a real application, it would also need to authenticate the user.)

@Name("login")
public class Login {
   
   @In
   private Actor actor;
   
   private String user;

   public String getUser() {
      return user;
   }

   public void setUser(String user) {
      this.user = user;
   }
   
   public String login()
   {
      actor.setId(user);
      return "/todo.jsp";
   }
}

Example 1.14. 



Here we see the use of @In to inject the built-in Actor component.

The JSP itself is trivial:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<f:view>
    <h:form>
      <div>
        <h:inputText value="#{login.user}"/>
        <h:commandButton value="Login" action="#{login.login}"/>
      </div>
    </h:form>
</f:view>
</body>
</html>

Example 1.15. 



The second JavaBean is responsible for starting business process instances, and ending tasks.

@Name("todoList")
public class TodoList {
   
   private String description;
   
   public String getDescription()
   {
      return description;
   }

   public void setDescription(String description) {
      this.description = description;
   }
   
   @CreateProcess(definition="todo")
   public void createTodo() {}
   
   @StartTask @EndTask
   public void done() {}

}
1

The description property accepts user input form the JSP page, and exposes it to the process definition, allowing the task description to be set.

2

The Seam @CreateProcess annotation creates a new jBPM process instance for the named process definition.

3

The Seam @StartTask annotation starts work on a task. The @EndTask ends the task, and allows the business process execution to resume.

Example 1.16. 



In a more realistic example, @StartTask and @EndTask would not appear on the same method, because there is usually work to be done using the application in order to complete the task.

Finally, the meat of the application is in todo.jsp:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://jboss.com/products/seam/taglib" prefix="s" %>
<html>
<head>
<title>Todo List</title>
</head>
<body>
<h1>Todo List</h1>
<f:view>
   <h:form id="list">
      <div>
         <h:outputText value="There are no todo items." rendered="#{empty 
                                       taskInstanceList}"/>
         <h:dataTable value="#{taskInstanceList}" var="task" rendered="#{not empty 
                                       taskInstanceList}">
            <h:column>
                <f:facet name="header">
                    <h:outputText value="Description"/>
                </f:facet>
                <h:inputText value="#{task.description}"/>
            </h:column>
            <h:column>
                <f:facet name="header">
                    <h:outputText value="Created"/>
                </f:facet>
                <h:outputText value="#{task.taskMgmtInstance.processInstance.start}">
                    <f:convertDateTime type="date"/>
                </h:outputText>
            </h:column>
            <h:column>
                <f:facet name="header">
                    <h:outputText value="Priority"/>
                </f:facet>
                <h:inputText value="#{task.priority}" style="width: 30"/>
            </h:column>
            <h:column>
                <f:facet name="header">
                    <h:outputText value="Due Date"/>