Seam - Contextual Components

A Framework for Enterprise Java

2.0.1.GA


Table of Contents

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.1.1. The entity bean: User.java
1.2.1.2. The stateless session bean class: RegisterAction.java
1.2.1.3. The session bean local interface: Register.java
1.2.1.4. The Seam component deployment descriptor: components.xml
1.2.1.5. The web deployment description: web.xml
1.2.1.6. The JSF configration: faces-config.xml
1.2.1.7. The EJB deployment descriptor: ejb-jar.xml
1.2.1.8. The EJB persistence deployment descriptor: persistence.xml
1.2.1.9. The view: register.xhtml and registered.xhtml
1.2.1.10. The EAR deployment descriptor: application.xml
1.2.2. How it works
1.3. Clickable lists in Seam: the messages example
1.3.1. Understanding the code
1.3.1.1. The entity bean: Message.java
1.3.1.2. The stateful session bean: MessageManagerBean.java
1.3.1.3. The session bean local interface: MessageManager.java
1.3.1.4. The view: messages.jsp
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. An example of Seam with Hibernate: the Hibernate Booking example
1.9. A RESTful Seam application: the Blog example
1.9.1. Using "pull"-style MVC
1.9.2. Bookmarkable search results page
1.9.3. Using "push"-style MVC in a RESTful application
2. Getting started with Seam, using seam-gen
2.1. Before you start
2.2. Setting up a new Eclipse project
2.3. Creating a new action
2.4. Creating a form with an action
2.5. Generating an application from an existing database
2.6. Generating an application from existing JPA/EJB3 entities
2.7. Deploying the application as an EAR
2.8. Seam and incremental hot deployment
2.9. Using Seam with JBoss 4.0
2.9.1. Install JBoss 4.0
2.9.2. Install the JSF 1.2 RI
3. The contextual component model
3.1. Seam contexts
3.1.1. Stateless context
3.1.2. Event context
3.1.3. Page context
3.1.4. Conversation context
3.1.5. Session context
3.1.6. Business process context
3.1.7. Application context
3.1.8. Context variables
3.1.9. Context search priority
3.1.10. Concurrency model
3.2. Seam components
3.2.1. Stateless session beans
3.2.2. Stateful session beans
3.2.3. Entity beans
3.2.4. JavaBeans
3.2.5. Message-driven beans
3.2.6. Interception
3.2.7. Component names
3.2.8. Defining the component scope
3.2.9. Components with multiple roles
3.2.10. Built-in components
3.3. Bijection
3.4. Lifecycle methods
3.5. Conditional installation
3.6. Logging
3.7. The Mutable interface and @ReadOnly
3.8. Factory and manager components
4. Configuring Seam components
4.1. Configuring components via property settings
4.2. Configuring components via components.xml
4.3. Fine-grained configuration files
4.4. Configurable property types
4.5. Using XML Namespaces
5. Events, interceptors and exception handling
5.1. Seam events
5.1.1. Page actions
5.1.1.1. Page parameters
5.1.1.2. Navigation
5.1.1.3. Fine-grained files for definition of navigation, page actions and parameters
5.1.2. Component-driven events
5.1.3. Contextual events
5.2. Seam interceptors
5.3. Managing exceptions
5.3.1. Exceptions and transactions
5.3.2. Enabling Seam exception handling
5.3.3. Using annotations for exception handling
5.3.4. Using XML for exception handling
5.3.5. Some common exceptions
6. Conversations and workspace management
6.1. Seam's conversation model
6.2. Nested conversations
6.3. Starting conversations with GET requests
6.4. Using <s:link> and <s:button>
6.5. Success messages
6.6. Natural conversation ids
6.6.1. Creating a natural conversation
6.6.2. Redirecting to a natural conversation
6.7. Workspace management
6.7.1. Workspace management and JSF navigation
6.7.2. Workspace management and jPDL pageflow
6.7.3. The conversation switcher
6.7.4. The conversation list
6.7.5. Breadcrumbs
6.8. Conversational components and JSF component bindings
6.9. Concurrent calls to conversational components
6.9.1. RichFaces Ajax
7. Pageflows and business processes
7.1. Pageflow in Seam
7.1.1. The two navigation models
7.1.2. Seam and the back button
7.2. Using jPDL pageflows
7.2.1. Installing pageflows
7.2.2. Starting pageflows
7.2.3. Page nodes and transitions
7.2.4. Controlling the flow
7.2.5. Ending the flow
7.2.6. Pageflow composition
7.3. Business process management in Seam
7.4. Using jPDL business process definitions
7.4.1. Installing process definitions
7.4.2. Initializing actor ids
7.4.3. Initiating a business process
7.4.4. Task assignment
7.4.5. Task lists
7.4.6. Performing a task
8. Seam and Object/Relational Mapping
8.1. Introduction
8.2. Seam managed transactions
8.2.1. Disabling Seam-managed transactions
8.2.2. Configuring a Seam transaction manager
8.2.3. Transaction synchronization
8.3. Seam-managed persistence contexts
8.3.1. Using a Seam-managed persistence context with JPA
8.3.2. Using a Seam-managed Hibernate session
8.3.3. Seam-managed persistence contexts and atomic conversations
8.4. Using the JPA "delegate"
8.5. Using EL in EJB-QL/HQL
8.6. Using Hibernate filters
9. JSF form validation in Seam
10. Groovy integration
10.1. Groovy introduction
10.2. Writing Seam applications in Groovy
10.2.1. Writing Groovy components
10.2.1.1. Entity
10.2.1.2. Seam component
10.2.2. seam-gen
10.3. Deployment
10.3.1. Deploying Groovy code
10.3.2. Native .groovy file deployment at development time
10.3.3. seam-gen
11. The Seam Application Framework
11.1. Introduction
11.2. Home objects
11.3. Query objects
11.4. Controller objects
12. Seam and JBoss Rules
12.1. Installing rules
12.2. Using rules from a Seam component
12.3. Using rules from a jBPM process definition
13. Security
13.1. Overview
13.1.1. Which mode is right for my application?
13.2. Requirements
13.3. Disabling Security
13.4. Authentication
13.4.1. Configuration
13.4.2. Writing an authentication method
13.4.2.1. Identity.addRole()
13.4.2.2. Special Considerations
13.4.3. Writing a login form
13.4.4. Simplified Configuration - Summary
13.4.5. Handling Security Exceptions
13.4.6. Login Redirection
13.4.7. HTTP Authentication
13.4.7.1. Writing a Digest Authenticator
13.4.8. Advanced Authentication Features
13.4.8.1. Using your container's JAAS configuration
13.5. Error Messages
13.6. Authorization
13.6.1. Core concepts
13.6.2. Securing components
13.6.2.1. The @Restrict annotation
13.6.2.2. Inline restrictions
13.6.3. Security in the user interface
13.6.4. Securing pages
13.6.5. Securing Entities
13.6.5.1. Entity security with JPA
13.6.5.2. Entity security with Hibernate
13.7. Writing Security Rules
13.7.1. Permissions Overview
13.7.2. Configuring a rules file
13.7.3. Creating a security rules file
13.7.3.1. Wildcard permission checks
13.8. SSL Security
13.9. CAPTCHA
13.9.1. Configuring the CAPTCHA Servlet
13.9.2. Adding a CAPTCHA to a form
13.9.3. Customising the CAPTCHA algorithm
13.10. Security Events
13.11. Extending the Identity component
14. Internationalization and themes
14.1. Locales
14.2. Labels
14.2.1. Defining labels
14.2.2. Displaying labels
14.2.3. Faces messages
14.3. Timezones
14.4. Themes
14.5. Persisting locale and theme preferences via cookies
15. Seam Text
15.1. Basic fomatting
15.2. Entering code and text with special characters
15.3. Links
15.4. Entering HTML
16. iText PDF generation
16.1. Using PDF Support
16.1.1. Creating a document
16.1.2. Basic Text Elements
16.1.3. Headers and Footers
16.1.4. Chapters and Sections
16.1.5. Lists
16.1.6. Tables
16.1.7. Document Constants
16.1.7.1. Color Values
16.1.7.2. Alignment Values
16.1.8. Configuring iText
16.2. Charting
16.3. Bar codes
16.4. Rendering Swing/AWT components
16.5. Further documentation
17. Email
17.1. Creating a message
17.1.1. Attachments
17.1.2. HTML/Text alternative part
17.1.3. Multiple recipients
17.1.4. Multiple messages
17.1.5. Templating
17.1.6. Internationalisation
17.1.7. Other Headers
17.2. Receiving emails
17.3. Configuration
17.3.1. mailSession
17.3.1.1. JNDI lookup in JBoss AS
17.3.1.2. Seam configured Session
17.4. Meldware
17.5. Tags
18. Asynchronicity and messaging
18.1. Asynchronicity
18.1.1. Asynchronous methods
18.1.2. Asynchronous methods with the Quartz Dispatcher
18.1.3. Asynchronous events
18.2. Messaging in Seam
18.2.1. Configuration
18.2.2. Sending messages
18.2.3. Receiving messages using a message-driven bean
18.2.4. Receiving messages in the client
19. Caching
19.1. Using JBossCache in Seam
19.2. Page fragment caching
20. Web Services
20.1. Configuration and Packaging
20.2. Conversational Web Services
20.2.1. A Recommended Strategy
20.3. An example web service
21. Remoting
21.1. Configuration
21.2. The "Seam" object
21.2.1. A Hello World example
21.2.2. Seam.Component
21.2.2.1. Seam.Component.newInstance()
21.2.2.2. Seam.Component.getInstance()
21.2.2.3. Seam.Component.getComponentName()
21.2.3. Seam.Remoting
21.2.3.1. Seam.Remoting.createType()
21.2.3.2. Seam.Remoting.getTypeName()
21.3. Evaluating EL Expressions
21.4. Client Interfaces
21.5. The Context
21.5.1. Setting and reading the Conversation ID
21.5.2. Remote calls within the current conversation scope
21.6. Batch Requests
21.7. Working with Data types
21.7.1. Primitives / Basic Types
21.7.1.1. String
21.7.1.2. Number
21.7.1.3. Boolean
21.7.2. JavaBeans
21.7.3. Dates and Times
21.7.4. Enums
21.7.5. Collections
21.7.5.1. Bags
21.7.5.2. Maps
21.8. Debugging
21.9. The Loading Message
21.9.1. Changing the message
21.9.2. Hiding the loading message
21.9.3. A Custom Loading Indicator
21.10. Controlling what data is returned
21.10.1. Constraining normal fields
21.10.2. Constraining Maps and Collections
21.10.3. Constraining objects of a specific type
21.10.4. Combining Constraints
21.11. JMS Messaging
21.11.1. Configuration
21.11.2. Subscribing to a JMS Topic
21.11.3. Unsubscribing from a Topic
21.11.4. Tuning the Polling Process
22. Seam and the Google Web Toolkit
22.1. Configuration
22.2. Preparing your component
22.3. Hooking up a GWT widget to the Seam component
22.4. GWT Ant Targets
23. Spring Framework integration
23.1. Injecting Seam components into Spring beans
23.2. Injecting Spring beans into Seam components
23.3. Making a Spring bean into a Seam component
23.4. Seam-scoped Spring beans
23.5. Using Spring PlatformTransactionManagement
23.6. Using a Seam Managed Persistence Context in Spring
23.7. Using a Seam Managed Hibernate Session in Spring
23.8. Spring Application Context as a Seam Component
23.9. Using a Spring TaskExecutor for @Asynchronous
24. Hibernate Search
24.1. Introduction
24.2. Configuration
24.3. Usage
25. Configuring Seam and packaging Seam applications
25.1. Basic Seam configuration
25.1.1. Integrating Seam with JSF and your servlet container
25.1.2. Using facelets
25.1.3. Seam Resource Servlet
25.1.4. Seam servlet filters
25.1.4.1. Exception handling
25.1.4.2. Conversation propagation with redirects
25.1.4.3. Multipart form submissions
25.1.4.4. Character encoding
25.1.4.5. RichFaces
25.1.4.6. Identity Logging
25.1.4.7. Context management for custom servlets
25.1.4.8. Adding custom filters
25.1.5. Integrating Seam with your EJB container
25.1.6. Don't forget!
25.2. Configuring Seam in Java EE 5
25.2.1. Packaging
25.3. Configuring Seam in J2EE
25.3.1. Boostrapping Hibernate in Seam
25.3.2. Boostrapping JPA in Seam
25.3.3. Packaging
25.4. Configuring Seam in Java SE, without JBoss Embedded
25.5. Configuring Seam in Java SE, with JBoss Embedded
25.5.1. Installing Embedded JBoss
25.5.2. Packaging
25.6. Configuring jBPM in Seam
25.6.1. Packaging
25.7. Configuring Seam in a Portal
25.8. Configuring SFSB and Session Timeouts in JBoss AS
26. Seam on OC4J
26.1. Installation and operation of OC4J
26.2. The jee5/booking example
26.2.1. Booking Example Dependencies
26.2.1.1. Core Seam dependencies
26.2.1.2. Extra dependencies
26.2.2. Configuration file changes
26.2.3. Building the jee5/booking example
26.3. Deploying the Seam application to OC4J
26.4. Deploying an application created using seam-gen to OC4J
26.4.1. Generating a basic seam-gen application
26.4.2. Changes needed for deployment to OC4J
26.4.2.1. Configuration file changes
26.4.2.2. Extra jar dependencies
26.4.3. Building and deploying the seam-gen'd application to OC4J
26.4.4. Extending example with reverse engineered CRUD and Drools
26.4.4.1. Have seam-gen generate your CRUD applications
26.4.4.2. Hook up drools authentication using your new CRUD application
26.5. Finishing up
27. Seam on BEA's Weblogic
27.1. Installation and operation of Weblogic
27.1.1. Installing 10.3.TP
27.1.2. Creating your Weblogic domain
27.1.3. How to Start/Stop/Access your domain
27.2. The jee5/booking example
27.2.1. EJB Blockers with Weblogic
27.2.1.1. Secondary issue with the Tech Preview
27.2.2. The jee5/booking example
27.2.2.1. Setting up the hsql datasource
27.2.2.2. Configuration and Build changes
27.2.2.3. Deploying the Application
27.3. The jpa booking example
27.3.1. Building and deploying jpa booking example
27.3.1.1. Setting up the datasource
27.3.1.2. Building the example
27.3.1.3. Deploying the example
27.3.2. What's different with Weblogic 10.x
27.4. Deploying an application created using seam-gen on Weblogic 10.x
27.4.1. Running seam-gen setup
27.4.2. What to change for Weblogic 10.X
27.4.2.1. Configuration file changes
27.4.2.2. Library changes
27.4.2.3. seam-gen development profile issue
27.4.3. Building and Deploying your application
27.4.3.1. Setting up the data source
27.4.3.2. Building the application
27.4.3.3. Deploying the example
28. Seam on IBM's Websphere
28.1. Websphere environment and deployment information
28.1.1. Installation versions and tips
28.1.2. Required custom properties
28.2. The jee5/booking example
28.2.1. Configuration file changes
28.2.2. Building the jee5/booking example
28.2.2.1. New libraries dependencies
28.2.2.2. Updating the build.xml file
28.2.3. Deploying the application to Websphere
28.3. The jpa booking example
28.3.1. Building the jpa example
28.3.2. Deploying the jpa example
28.3.3. Whats different for Websphere 6.1
28.4. Deploying an application created using seam-gen on Websphere 6.1.0.13
28.5. Changes needed for deployment to Websphere
28.5.1. Configuration file changes
28.5.2. Creating the AuthenticatorAction EJB
28.5.3. Extra jar dependencies and other changes to the build.xml
28.5.4. Building and deploying the seam-gen'd application to Websphere
29. Seam annotations
29.1. Annotations for component definition
29.2. Annotations for bijection
29.3. Annotations for component lifecycle methods
29.4. Annotations for context demarcation
29.5. Annotations for use with Seam JavaBean components in a J2EE environment
29.6. Annotations for exceptions
29.7. Annotations for Seam Remoting
29.8. Annotations for Seam interceptors
29.9. Annotations for asynchronicity
29.10. Annotations for use with JSF
29.10.1. Annotations for use with dataTable
29.11. Meta-annotations for databinding
29.12. Annotations for packaging
29.13. Annotations for integrating with the servlet container
30. Built-in Seam components
30.1. Context injection components
30.2. Utility components
30.3. Components for internationalization and themes
30.4. Components for controlling conversations
30.5. jBPM-related components
30.6. Security-related components
30.7. JMS-related components
30.8. Mail-related components
30.9. Infrastructural components
30.10. Miscellaneous components
30.11. Special components
31. Seam JSF controls
31.1. Tags
31.2. Annotations
32. JBoss EL
32.1. Parameterized Expressions
32.1.1. Usage
32.1.2. Limitations and Hints
32.2. Projection
33. Testing Seam applications
33.1. Unit testing Seam components
33.2. Integration testing Seam components
33.2.1. Using mocks in integration tests
33.3. Integration testing Seam application user interactions
33.3.1. Configuration
33.3.2. Integration Testing with Mock Data
33.3.3. Integration Testing Seam Mail
34. Seam tools
34.1. jBPM designer and viewer
34.1.1. Business process designer
34.1.2. Pageflow viewer
35. Dependencies
35.1. Project Dependencies
35.1.1. Core
35.1.2. RichFaces
35.1.3. Seam Mail
35.1.4. Seam PDF
35.1.5. JBoss Rules
35.1.6. JBPM
35.1.7. GWT
35.1.8. Spring
35.1.9. Groovy
35.2. Dependency Management using Maven

Introduction to JBoss Seam

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

One kind of "stuff"

Seam defines a uniform component model for all business logic in your application. A Seam component may be stateful, with the state associated with any one of several well-defined contexts, including the long-running, persistent, business process context and the conversation context, which is preserved across multiple web requests in a user interaction.

There is no distinction between presentation tier components and business logic components in Seam. You can layer your application according to whatever architecture you devise, rather than being forced to shoehorn your application logic into an unnatural layering scheme forced upon you by whatever combination of stovepipe frameworks you're using today.

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.

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 with other frameworks.

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

It is possible to write Seam applications where "everything" is an EJB. This may come as a surprise if you're used to thinking of EJBs as coarse-grained, so-called "heavyweight" objects. However, version 3.0 has completely changed 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!

On the other hand, if you prefer not to adopt EJB 3.0 at this time, you don't have to. Virtually any Java class may be a Seam component, and Seam provides all the functionality that you expect from a "lightweight" container, and more, for any component, EJB or otherwise.

Integrated AJAX

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

Alternatively, Seam provides a built-in JavaScript remoting layer that lets you call components asynchronously from client-side JavaScript without the need for an intermediate action layer. You can even subscribe to server-side JMS topics and receive messages via AJAX push.

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.

Business process as a first class construct

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

Seam even allows you to define presentation tier pageflow using the same language (jPDL) that jBPM uses for business process definition.

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.

Declarative state management

We're all used to the concept of declarative transaction management and declarative security from the early days of EJB. 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 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.

You'll be amazed at how many things become easier once you start using conversations. Have you ever suffered pain dealing with lazy association fetching in an ORM solution like Hibernate or JPA? Seam's conversation-scoped persistence contexts mean you'll rarely have to see a LazyInitializationException. Have you ever had problems with the refresh button? The back button? With duplicate form submission? With propagating messages across a post-then-redirect? Seam's conversation management solves these problems without you even needing to really think about them. They're all symptoms of the broken state management architecture that has been prevalent since the earliest days of the web.

Bijection

The notion of Inversion of Control or dependency injection exists in both JSF and EJB3, as well as in numerous so-called "lightweight 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, and because components belonging to wider scopes may not be injected into components belonging to narrower scopes.

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 it to an attribute of the component.

Workspace management and multi-window browsing

Seam applications let the user freely switch between multiple browser tabs, each associated with a different, safely isolated, conversation. Applications may even take advantage of workspace management, allowing the user to switch between conversations (workspaces) in a single browser tab. Seam provides not only correct multi-window operation, but also multi-window-like operation in a single window!

Prefer annotations to XML

Traditionally, the Java community has been in a state of deep confusion about precisely what kinds of meta-information counts as configuration. J2EE and popular "lightweight" containers have provided XML-based deployment descriptors both for things which are truly configurable between different deployments of the system, and for any other kinds or declaration which can not easily be expressed in Java. Java 5 annotations changed all this.

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).

Integration testing is easy

Seam components, being plain Java classes, 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 using JBoss Embedded.

The specs ain't perfect

We think the latest incarnation of Java EE is great. But we know it's never going to be perfect. Where there are holes in the specifications (for example, limitations in the JSF lifecycle for GET requests), Seam fixes them. And the authors of Seam are working with the JCP expert groups to make sure those fixes make their way back into the next revision of the standards.

There's more to a web application than serving HTML pages

Today's web frameworks think too small. They let you get user input off a form and into your Java objects. And then they leave you hanging. A truly complete web application framework should address problems like persistence, concurrency, asynchronicity, state management, security, email, messaging, PDF and chart generation, workflow, wikitext rendering, webservices, caching and more. Once you scratch the surface of Seam, you'll be amazed at how many problems become simpler...

Seam integrates JPA and Hibernate3 for persistence, the EJB Timer Service and Quartz for lightweight asychronicity, jBPM for workflow, JBoss Rules for business rules, Meldware Mail for email, Hibernate Search and Lucene for full text search, JMS for messaging and JBoss Cache for page fragment caching. Seam layers an innovative rule-based security framework over JAAS and JBoss Rules. There's even JSF tag libraries for rendering PDF, outgoing email, charts and wikitext. Seam components may be called synchronously as a Web Service, asynchronously from client-side JavaScript or Google Web Toolkit or, of course, directly from JSF.

Get started now!

Seam works in any Java EE application server, and even works in Tomcat. If your environment supports EJB 3.0, great! If it doesn't, no problem, you can use Seam's built-in transaction management with JPA or Hibernate3 for persistence. Or, you can deploy JBoss Embedded in Tomcat, and get full support for EJB 3.0.

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 have downloaded JBoss AS 4.2.0. You should also have a copy of Seam downloaded and extracted to a work directory.

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 4.2.0 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.

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 6.0 installation in the build.properties file in the root folder of your Seam installation. You will need to follow the instructions in Section 25.5.1, “Installing Embedded JBoss” for installing JBoss Embedded on Tomcat 6.0. JBoss Embedded is required to run the Seam demo applications on Tomcat. (However, it is possible to use Seam on Tomcat without JBoss Embedded.)

Now, build and deploy the example by typing ant tomcat.deploy 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.

Example 1.1. 

@Entity                                                                                  (1)
@Name("user")                                                                            (2)
@Scope(SESSION)                                                                          (3)
@Table(name="users")                                                                     (4)
public class User implements Serializable
{
   private static final long serialVersionUID = 1881413500711441951L;
   
   private String username;                                                              (5)
   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() {}                                                                      (6)
   
   @NotNull @Length(min=5, max=15)                                                       (7)
   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)                                                   (8)
   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.

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!

Example 1.2. 

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

   @In                                                                                   (2)
   private User user;
   
   @PersistenceContext                                                                   (3)
   private EntityManager em;
   
   @Logger                                                                               (4)
   private Log log;
   
   public String register()                                                              (5)
   {
      List existing = em.createQuery(
         "select username from User where username=#{user.username}")                    (6)
         .getResultList();
         
      if (existing.size()==0)
      {
         em.persist(user);
         log.info("Registered new user #{user.username}");                               (7)
         return "/registered.xhtml";                                                     (8)
      }
      else
      {
         FacesMessages.instance().add("User #{user.username} already exists");           (9)
         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.

1.2.1.3. The session bean local interface: Register.java

Naturally, our session bean needs a local interface.

Example 1.3. 

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

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:

Example 1.4. 

<?xml version="1.0" encoding="UTF-8"?>
<components xmlns="http://jboss.com/products/seam/components"
            xmlns:core="http://jboss.com/products/seam/core"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation=
                "http://jboss.com/products/seam/core http://jboss.com/products/seam/core-2.0.xsd 
                 http://jboss.com/products/seam/components http://jboss.com/products/seam/components-2.0.xsd">
            
     <core:init jndi-pattern="@jndiPattern@"/>
     
</components>

This code configures a property named jndiPattern of a built-in Seam component named org.jboss.seam.core.init. The funny @ symbols are there because our Ant build script puts the correct JNDI pattern in when we deploy the application.

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.

Example 1.5. 

<?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>

    <!-- JSF -->
              
    <listener>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>
    
    <context-param>
        <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
        <param-value>.xhtml</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>
              
    <session-config>
        <session-timeout>10</session-timeout>
    </session-config>

</web-app>

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

1.2.1.6. The JSF configration: faces-config.xml

Most Seam applications use JSF views as the presentation layer. So usually we'll need faces-config.xml. In our case, we are going to use Facelets for defining our views, so we need to tell JSF to use Facelets as its templating engine.

Example 1.6. 

<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="1.2"
              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-facesconfig_1_2.xsd">

    <!-- Facelets support -->
    <application>
        <view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
    </application>
    
</faces-config>

Note that we don't need any JSF managed bean declarations! Our managed beans are annotated 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 orchestration: navigation rules or 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.xhtml and registered.xhtml

The view pages for a Seam application could be implemented using any technology that supports JSF. In this example we use Facelets, because we think it's better than JSP.

Example 1.7. 

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:s="http://jboss.com/products/seam/taglib"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">

   <head>
      <title>Register New User</title>
   </head>
   <body>
      <f:view>
         <h:form>
            <s:validateAll>
               <h:panelGrid columns="2">
                  Username: <h:inputText value="#{user.username}" required="true"/>
                  Real Name: <h:inputText value="#{user.name}" required="true"/>
                  Password: <h:inputSecret value="#{user.password}" required="true"/>
               </h:panelGrid>
            </s:validateAll>
            <h:messages/>
            <h:commandButton value="Register" action="#{register.register}"/>
         </h:form>
      </f:view>
   </body>

</html>

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.

Example 1.8. 

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core">

   <head>
      <title>Successfully Registered New User</title>
   </head>
   <body>
      <f:view>
         Welcome, #{user.name}, you are successfully registered as #{user.username}.
      </f:view>
   </body>

</html>

This is a boring old Facelets page using some embedded EL. 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.

Example 1.9. 

<?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>
        <ejb>jboss-seam.jar</ejb>
    </module>
    <module>
        <java>jboss-el.jar</java>
    </module>

</application>

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

We've now seen all the files in the entire application!

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.xhtml" outcome triggers a browser redirect to the registered.xhtml 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:

Example 1.10. 

@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;
   }
   
}

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.

Example 1.11. 

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

   @DataModel                                                                            (1)
   private List<Message> messageList;
   
   @DataModelSelection                                                                   (2)
   @Out(required=false)                                                                  (3)
   private Message message;
   
   @PersistenceContext(type=EXTENDED)                                                    (4)
   private EntityManager em;
   
   @Factory("messageList")                                                               (5)
   public void findMessages()
   {
      messageList = em.createQuery("from Message msg order by msg.datetime desc")
                      .getResultList();
   }
   
   public void select()                                                                  (6)
   {
      message.setRead(true);
   }
   
   public void delete()                                                                  (7)
   {
      messageList.remove(message);
      em.remove(message);
      message=null;
   }
   
   @Remove                                                                               (8)
   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 with no parameters marked @Remove that Seam uses to remove the stateful bean when the Seam context ends, and clean up any server-side state.

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.

Example 1.12. 

<%@ 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>

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:

Example 1.13. 

<process-definition name="todo">
   
   <start-state name="start">                                                            (1)
      <transition to="todo"/>
   </start-state>
   
   <task-node name="todo">                                                               (2)
      <task name="todo" description="#{todoList.description}">                           (3)
         <assignment actor-id="#{actor.id}"/>                                            (4)
      </task>
      <transition to="done"/>
   </task-node>
   
   <end-state name="done"/>                                                              (5)
   
</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.

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.)

Example 1.14. 

@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";
   }
}

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

The JSP itself is trivial:

Example 1.15. 

<%@ 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>

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

Example 1.16. 

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

   public void setDescription(String description) {
      this.description = description;
   }
   
   @CreateProcess(definition="todo")                                                     (2)
   public void createTodo() {}
   
   @StartTask @EndTask                                                                   (3)
   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.

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 applicati