SeamFramework.orgCommunity Documentation

Seam - Contextual Components

A Framework for Enterprise Java

2.3.0.Final


Introduction to JBoss Seam
1. Contribute to Seam
1. Seam Tutorial
1.1. Using the Seam examples
1.1.1. Running the examples on JBoss AS
1.1.2. 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 Debug Page
1.7. Nested conversations: extending the Hotel Booking example
1.7.1. Introduction
1.7.2. Understanding Nested Conversations
1.8. A complete application featuring Seam and jBPM: the DVD Store example
1.9. Bookmarkable URLs with 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 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
3. Getting started with Seam, using JBoss Tools
3.1. Before you start
4. Migration from 2.2 to 2.3
4.1. Migration of XML Schemas
4.1.1. Seam schema migration
4.1.2. Java EE 6 schema changes
4.2. Java EE 6 upgrade
4.2.1. Using Bean Validation standard instead of Hibernate Validator
4.2.2. Migration of JSF 1 to JSF 2 Facelets templates
4.2.3. Migration to JPA 2.0
4.2.4. Using compatible JNDI for resources
4.3. JBoss AS 7.1 deployment
4.3.1. Deployment changes
4.3.2. Datasource migration
4.4. Changes in testing framework
4.5. Dependency changes with using Maven
4.5.1. Seam Bill of Materials
5. The contextual component model
5.1. Seam contexts
5.1.1. Stateless context
5.1.2. Event context
5.1.3. Page context
5.1.4. Conversation context
5.1.5. Session context
5.1.6. Business process context
5.1.7. Application context
5.1.8. Context variables
5.1.9. Context search priority
5.1.10. Concurrency model
5.2. Seam components
5.2.1. Stateless session beans
5.2.2. Stateful session beans
5.2.3. Entity beans
5.2.4. JavaBeans
5.2.5. Message-driven beans
5.2.6. Interception
5.2.7. Component names
5.2.8. Defining the component scope
5.2.9. Components with multiple roles
5.2.10. Built-in components
5.3. Bijection
5.4. Lifecycle methods
5.5. Conditional installation
5.6. Logging
5.7. The Mutable interface and @ReadOnly
5.8. Factory and manager components
6. Configuring Seam components
6.1. Configuring components via property settings
6.2. Configuring components via components.xml
6.3. Fine-grained configuration files
6.4. Configurable property types
6.5. Using XML Namespaces
7. Events, interceptors and exception handling
7.1. Seam events
7.2. Page actions
7.3. Page parameters
7.3.1. Mapping request parameters to the model
7.4. Propagating request parameters
7.5. URL rewriting with page parameters
7.6. Conversion and Validation
7.7. Navigation
7.8. Fine-grained files for definition of navigation, page actions and parameters
7.9. Component-driven events
7.10. Contextual events
7.11. Seam interceptors
7.12. Managing exceptions
7.12.1. Exceptions and transactions
7.12.2. Enabling Seam exception handling
7.12.3. Using annotations for exception handling
7.12.4. Using XML for exception handling
7.12.5. Some common exceptions
8. Conversations and workspace management
8.1. Seam's conversation model
8.2. Nested conversations
8.3. Starting conversations with GET requests
8.4. Requiring a long-running conversation
8.5. Using <s:link> and <s:button>
8.6. Success messages
8.7. Natural conversation ids
8.8. Creating a natural conversation
8.9. Redirecting to a natural conversation
8.10. Workspace management
8.10.1. Workspace management and JSF navigation
8.10.2. Workspace management and jPDL pageflow
8.10.3. The conversation switcher
8.10.4. The conversation list
8.10.5. Breadcrumbs
8.11. Conversational components and JSF component bindings
8.12. Concurrent calls to conversational components
8.12.1. How should we design our conversational AJAX application?
8.12.2. Dealing with errors
9. Pageflows and business processes
9.1. Pageflow in Seam
9.1.1. The two navigation models
9.1.2. Seam and the back button
9.2. Using jPDL pageflows
9.2.1. Installing pageflows
9.2.2. Starting pageflows
9.2.3. Page nodes and transitions
9.2.4. Controlling the flow
9.2.5. Ending the flow
9.2.6. Pageflow composition
9.3. Business process management in Seam
9.4. Using jPDL business process definitions
9.4.1. Installing process definitions
9.4.2. Initializing actor ids
9.4.3. Initiating a business process
9.4.4. Task assignment
9.4.5. Task lists
9.4.6. Performing a task
10. Seam and Object/Relational Mapping
10.1. Introduction
10.2. Seam managed transactions
10.2.1. Disabling Seam-managed transactions
10.2.2. Configuring a Seam transaction manager
10.2.3. Transaction synchronization
10.3. Seam-managed persistence contexts
10.3.1. Using a Seam-managed persistence context with JPA
10.3.2. Using a Seam-managed Hibernate session
10.3.3. Seam-managed persistence contexts and atomic conversations
10.4. Using the JPA "delegate"
10.5. Using EL in EJB-QL/HQL
10.6. Using Hibernate filters
11. JSF form validation in Seam
12. Groovy integration
12.1. Groovy introduction
12.2. Writing Seam applications in Groovy
12.2.1. Writing Groovy components
12.2.2. seam-gen
12.3. Deployment
12.3.1. Deploying Groovy code
12.3.2. Native .groovy file deployment at development time
12.3.3. seam-gen
13. Writing your presentation layer using Apache Wicket
13.1. Adding Seam to your wicket application
13.1.1. Bijection
13.1.2. Orchestration
13.2. Setting up your project
13.2.1. Runtime instrumentation
13.2.2. Compile-time instrumentation
13.2.3. The @SeamWicketComponent annotation
13.2.4. Defining the Application
14. The Seam Application Framework
14.1. Introduction
14.2. Home objects
14.3. Query objects
14.4. Controller objects
15. Seam and JBoss Rules
15.1. Installing rules
15.2. Using rules from a Seam component
15.3. Using rules from a jBPM process definition
16. Security
16.1. Overview
16.2. Disabling Security
16.3. Authentication
16.3.1. Configuring an Authenticator component
16.3.2. Writing an authentication method
16.3.3. Writing a login form
16.3.4. Configuration Summary
16.3.5. Remember Me
16.3.6. Handling Security Exceptions
16.3.7. Login Redirection
16.3.8. HTTP Authentication
16.3.9. Advanced Authentication Features
16.4. Identity Management
16.4.1. Configuring IdentityManager
16.4.2. JpaIdentityStore
16.4.3. LdapIdentityStore
16.4.4. Writing your own IdentityStore
16.4.5. Authentication with Identity Management
16.4.6. Using IdentityManager
16.5. Error Messages
16.6. Authorization
16.6.1. Core concepts
16.6.2. Securing components
16.6.3. Security in the user interface
16.6.4. Securing pages
16.6.5. Securing Entities
16.6.6. Typesafe Permission Annotations
16.6.7. Typesafe Role Annotations
16.6.8. The Permission Authorization Model
16.6.9. RuleBasedPermissionResolver
16.6.10. PersistentPermissionResolver
16.7. Permission Management
16.7.1. PermissionManager
16.7.2. Permission checks for PermissionManager operations
16.8. SSL Security
16.8.1. Overriding the default ports
16.9. CAPTCHA
16.9.1. Configuring the CAPTCHA Servlet
16.9.2. Adding a CAPTCHA to a form
16.9.3. Customising the CAPTCHA algorithm
16.10. Security Events
16.11. Run As
16.12. Extending the Identity component
16.13. OpenID
16.13.1. Configuring OpenID
16.13.2. Presenting an OpenIdDLogin form
16.13.3. Logging in immediately
16.13.4. Deferring login
16.13.5. Logging out
17. Internationalization, localization and themes
17.1. Internationalizing your app
17.1.1. Application server configuration
17.1.2. Translated application strings
17.1.3. Other encoding settings
17.2. Locales
17.3. Labels
17.3.1. Defining labels
17.3.2. Displaying labels
17.3.3. Faces messages
17.4. Timezones
17.5. Themes
17.6. Persisting locale and theme preferences via cookies
18. Seam Text
18.1. Basic fomatting
18.2. Entering code and text with special characters
18.3. Links
18.4. Entering HTML
18.5. Using the SeamTextParser
19. iText PDF generation
19.1. Using PDF Support
19.1.1. Creating a document
19.1.2. Basic Text Elements
19.1.3. Headers and Footers
19.1.4. Chapters and Sections
19.1.5. Lists
19.1.6. Tables
19.1.7. Document Constants
19.2. Charting
19.3. Bar codes
19.4. Fill-in-forms
19.5. Rendering Swing/AWT components
19.6. Configuring iText
19.7. Further documentation
20. The Microsoft® Excel® spreadsheet application
20.1. The Microsoft® Excel® spreadsheet application support
20.2. Creating a simple workbook
20.3. Workbooks
20.4. Worksheets
20.5. Columns
20.6. Cells
20.6.1. Validation
20.6.2. Format masks
20.7. Formulas
20.8. Images
20.9. Hyperlinks
20.10. Headers and footers
20.11. Print areas and titles
20.12. Worksheet Commands
20.12.1. Grouping
20.12.2. Page breaks
20.12.3. Merging
20.13. Datatable exporter
20.14. Fonts and layout
20.14.1. Stylesheet links
20.14.2. Fonts
20.14.3. Borders
20.14.4. Background
20.14.5. Column settings
20.14.6. Cell settings
20.14.7. The datatable exporter
20.14.8. Layout examples
20.14.9. Limitations
20.15. Internationalization
20.16. Links and further documentation
21. RSS support
21.1. Installation
21.2. Generating feeds
21.3. Feeds
21.4. Entries
21.5. Links and further documentation
22. Email
22.1. Creating a message
22.1.1. Attachments
22.1.2. HTML/Text alternative part
22.1.3. Multiple recipients
22.1.4. Multiple messages
22.1.5. Templating
22.1.6. Internationalisation
22.1.7. Other Headers
22.2. Receiving emails
22.3. Configuration
22.3.1. mailSession
22.4. Tags
23. Asynchronicity and messaging
23.1. Messaging in Seam
23.1.1. Configuration
23.1.2. Sending messages
23.1.3. Receiving messages using a message-driven bean
23.1.4. Receiving messages in the client
23.2. Asynchronicity
23.2.1. Asynchronous methods
23.2.2. Asynchronous methods with the Quartz Dispatcher
23.2.3. Asynchronous events
23.2.4. Handling exceptions from asynchronous calls
24. Caching
24.1. Using Caching in Seam
24.2. Page fragment caching
25. Web Services
25.1. Configuration and Packaging
25.2. Conversational Web Services
25.2.1. A Recommended Strategy
25.3. An example web service
25.4. RESTful HTTP webservices with RESTEasy
25.4.1. RESTEasy configuration and request serving
25.4.2. Resources as Seam components
25.4.3. Securing resources
25.4.4. Mapping exceptions to HTTP responses
25.4.5. Exposing entities via RESTful API
25.4.6. Testing resources and providers
26. Remoting
26.1. Configuration
26.2. The "Seam" object
26.2.1. A Hello World example
26.2.2. Seam.Component
26.2.3. Seam.Remoting
26.3. Client Interfaces
26.4. The Context
26.4.1. Setting and reading the Conversation ID
26.4.2. Remote calls within the current conversation scope
26.5. Batch Requests
26.6. Working with Data types
26.6.1. Primitives / Basic Types
26.6.2. JavaBeans
26.6.3. Dates and Times
26.6.4. Enums
26.6.5. Collections
26.7. Debugging
26.8. Handling Exceptions
26.9. The Loading Message
26.9.1. Changing the message
26.9.2. Hiding the loading message
26.9.3. A Custom Loading Indicator
26.10. Controlling what data is returned
26.10.1. Constraining normal fields
26.10.2. Constraining Maps and Collections
26.10.3. Constraining objects of a specific type
26.10.4. Combining Constraints
26.11. Transactional Requests
26.12. JMS Messaging
26.12.1. Configuration
26.12.2. Subscribing to a JMS Topic
26.12.3. Unsubscribing from a Topic
26.12.4. Tuning the Polling Process
27. Seam and the Google Web Toolkit
27.1. Configuration
27.2. Preparing your component
27.3. Hooking up a GWT widget to the Seam component
27.4. GWT Ant Targets
27.5. GWT Maven plugin
28. Spring Framework integration
28.1. Injecting Seam components into Spring beans
28.2. Injecting Spring beans into Seam components
28.3. Making a Spring bean into a Seam component
28.4. Seam-scoped Spring beans
28.5. Using Spring PlatformTransactionManagement
28.6. Using a Seam Managed Persistence Context in Spring
28.7. Using a Seam Managed Hibernate Session in Spring
28.8. Spring Application Context as a Seam Component
28.9. Using a Spring TaskExecutor for @Asynchronous
29. Guice integration
29.1. Creating a hybrid Seam-Guice component
29.2. Configuring an injector
29.3. Using multiple injectors
30. Hibernate Search
30.1. Introduction
30.2. Configuration
30.3. Usage
31. Configuring Seam and packaging Seam applications
31.1. Basic Seam configuration
31.1.1. Integrating Seam with JSF and your servlet container
31.1.2. Seam Resource Servlet
31.1.3. Seam servlet filters
31.1.4. Integrating Seam with your EJB container
31.1.5. Don't forget!
31.2. Using Alternate JPA Providers
31.3. Configuring Seam in Java EE 6
31.3.1. Packaging
31.4. Configuring Seam without EJB
31.4.1. Boostrapping Hibernate in Seam
31.4.2. Boostrapping JPA in Seam
31.4.3. Packaging
31.5. Configuring Seam in Java SE
31.6. Configuring jBPM in Seam
31.6.1. Packaging
31.7. Deployment in JBoss AS 7
31.8. Configuring SFSB and Session Timeouts in JBoss AS 7
31.9. Running Seam in a Portlet
31.10. Deploying custom resources
32. Seam annotations
32.1. Annotations for component definition
32.2. Annotations for bijection
32.3. Annotations for component lifecycle methods
32.4. Annotations for context demarcation
32.5. Annotations for use with Seam JavaBean components in a J2EE environment
32.6. Annotations for exceptions
32.7. Annotations for Seam Remoting
32.8. Annotations for Seam interceptors
32.9. Annotations for asynchronicity
32.10. Annotations for use with JSF
32.10.1. Annotations for use with dataTable
32.11. Meta-annotations for databinding
32.12. Annotations for packaging
32.13. Annotations for integrating with the servlet container
33. Built-in Seam components
33.1. Context injection components
33.2. JSF-related components
33.3. Utility components
33.4. Components for internationalization and themes
33.5. Components for controlling conversations
33.6. jBPM-related components
33.7. Security-related components
33.8. JMS-related components
33.9. Mail-related components
33.10. Infrastructural components
33.11. Miscellaneous components
33.12. Special components
34. Seam JSF controls
34.1. Tags
34.1.1. Navigation Controls
34.1.2. Converters and Validators
34.1.3. Formatting
34.1.4. Seam Text
34.1.5. Form support
34.1.6. Other
34.2. Annotations
35. JBoss EL
35.1. Parameterized Expressions
35.1.1. Usage
35.1.2. Limitations and Hints
35.2. Projection
36. Clustering and EJB Passivation
36.1. Clustering
36.1.1. Programming for clustering
36.1.2. Deploying a Seam application to a JBoss AS cluster with session replication
36.1.3. Validating the distributable services of an application running in a JBoss AS cluster
36.2. EJB Passivation and the ManagedEntityInterceptor
36.2.1. The friction between passivation and persistence
36.2.2. Case #1: Surviving EJB passivation
36.2.3. Case #2: Surviving HTTP session replication
36.2.4. ManagedEntityInterceptor wrap-up
37. Performance Tuning
37.1. Bypassing Interceptors
38. Testing Seam applications
38.1. Unit testing Seam components
38.2. Integration testing Seam components
38.2.1. Configuration
38.2.2. Using JUnitSeamTest with Arquillian
38.2.3. Integration testing Seam application user interactions
39. Dependencies
39.1. JDK Dependencies
39.1.1. Oracle's JDK 6 Considerations
39.2. Project Dependencies
39.2.1. Core
39.2.2. RichFaces
39.2.3. Seam Mail
39.2.4. Seam PDF
39.2.5. Seam Microsoft Excel
39.2.6. Seam RSS support
39.2.7. Drools
39.2.8. JBPM
39.2.9. GWT
39.2.10. Spring
39.2.11. Groovy
39.3. Dependency Management using Maven

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 Java EE 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 Java EE 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 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 EJB 3, 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 with Java EE6

While Seam 2.2 was targeted Java EE 5 mainly, you can use some Java EE 6 technologies also on Seam 2.3.x.

Seam 2 and some of its extensions/implementations were added into Java EE 6 as CDI technology. So this should be a current focus of majority users. But for previous Seam 2.2 users who doesn't want or can't use pure Java EE 6, we bring some new features from the Java EE 6 set like JSF 2, JPA 2 and Bean Validation integrations into Seam 2.3.x.

Integrated AJAX

Seam supports the best open source JSF-based AJAX solutions: 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 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, Java EE 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. Java EE 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. You can run these tests directly inside your IDE, where Seam will automatically deploy EJB components using Arquillian.

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 Hibernate 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 should work in any Java EE application server, and even works in Tomcat. If your environment supports EJB 3.0 or 3.1, great! If it doesn't, no problem, you can use Seam's built-in transaction management with JPA or Hibernate for persistence.

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

Visit SeamFramework.org to find out how to contribute to Seam!

Seam provides a number of example applications demonstrating how to use the various features of Seam. This tutorial will guide you through a few of those examples to help you get started learning Seam. The Seam examples are located in the examples subdirectory of the Seam distribution. The registration example, which will be the first example we look at, is in the examples/registration directory.

Each example has the very similar directory structure which is based on Maven project structure defaults:

  • The <example>-ear directory contains enterprise application submodule files such as aggregator for web application files, EJB project.

  • The <example>-web directory contains web application submodule view-related files such as web page templates, images and stylesheets.

  • The <example>-ejb directory contains Enterprise Java Beans components.

  • The <example>-tests directory contains integration and functional tests.

  • The <example>-web/src/main/webapp directory contains view-related files such as web page templates, images and stylesheets.

  • The <example>-[ear|ejb]/src/main/resources directory contains deployment descriptors and other configuration files.

  • The <example>-ejb/src/main/java directory contains the application source code.

The example applications run on JBoss AS 7.1.1 with no additional configuration. The following sections will explain the procedure. Note that all the examples are built and run from the Maven pom.xml, so you'll need at least version 3.x of Maven installed before you get started. At the time of writing this text recent version of Maven was 3.0.4.

The registration example is a simple 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.

The example is implemented with two Facelets templates, one entity bean and one stateless session bean. Let's take a look at the code, starting from the "bottom".

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. User.java

(1)@Entity

(2)@Name("user")
(3)@Scope(SESSION)
(4)@Table(name="users")
public class User implements Serializable
{
   private static final long serialVersionUID = 1881413500711441951L;
   
(5)   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;
   }
   
(6)   public User() {}
   
(7)   @NotNull @Size(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;
   }
   
(8)   @Id @NotNull @Size(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 @Size annotations are part of the Bean Validation annotations specification (JSR-303). Seam integrates Bean Validation through Hibernate Validator, which is the reference implementation, 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 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 JSF 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.

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. RegisterAction.java

(1)@Stateless

@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 @Stateless annotation marks this class as a 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 session 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 which can also make use of JSF EL expressions.

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. (As of Seam 2.1, you can use StatusMessages instead to remove the semantic dependency on JSF). Built-in Seam components may be obtained by injection, or by calling the instance() method on the class of the built-in component.


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, which is the only sensible value.

Our session bean action listener performs the business and persistence logic for our mini-application. In more complex applications, we might need require a separate service layer. This is easy to achieve with Seam, but it's overkill for most web applications. Seam does not force you into any particular strategy for application layering, allowing your application to be as simple, or as complex, as you want.

Note that in this simple application, we've actually made it far more complex than it needs to be. If we had used the Seam application framework controllers, we would have eliminated all of our application code. However, then we wouldn't have had much of an application to explain.

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


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 Bean Validation annotations specified on the entity bean.


This is a simple Facelets page using some inline EL. There's nothing specific to Seam here.

Since this is the first Seam app we've seen, we'll take a look at the deployment descriptors. Before we get into them, it is worth noting that Seam strongly values minimal configuration. These configuration files will be created for you when you create a Seam application. You'll never need to touch most of these files. We're presenting them now only to help you understand what all the pieces in the example are doing.

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:


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 Maven build puts the correct JNDI pattern in when we deploy the application, which it reads from the components.properties file. You learn more about how this process works in Section 6.2, “Configuring components via components.xml”.

Note

Eclipse M2e Web tools plugin can't use the @ for token property filtering. Fortunately there works the other way which is in Maven filtering defined - ${property}.

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


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

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 Bean 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 uses the JNDI pattern mentioned earlier to locate the stateless session bean, wraps it as a Seam component, and returns it. Seam then presents this component to JSF and JSF invokes the register() action listener method.

But Seam is not done yet. Seam intercepts the method call and injects the User entity from the Seam session context, before allowing the invocation to continue.

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.

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.

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

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. MessageManagerBean.java

@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("select msg 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 attribute 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 every 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 JSF 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.)

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

Example 1.13. messages.xhtml


<?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.org/schema/seam/taglib"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
 <h:head>
  <title>Messages</title>
 </h:head>
 <h:body>
  <f:view>
     <h2>Message List</h2>
     <h:outputText id="noMessages" value="No messages to display" rendered="#{messageList.rowCount==0}"/>
     <h:dataTable id="messages" var="msg" value="#{messageList}" rendered="#{messageList.rowCount>0}">
        <h:column>
           <f:facet name="header">
              <h:outputText value="Read"/>
           </f:facet>
           <h:selectBooleanCheckbox id="read" value="#{msg.read}" disabled="true"/>
        </h:column>
        <h:column>
           <f:facet name="header">
              <h:outputText value="Title"/>
           </f:facet>
           <s:link id="link" value="#{msg.title}" action="#{messageManager.select}"/>
        </h:column>
        <h:column>
           <f:facet name="header">
              <h:outputText value="Date/Time"/>
           </f:facet>
           <h:outputText id="date" value="#{msg.datetime}">
              <f:convertDateTime type="both" dateStyle="medium" timeStyle="short"/>
           </h:outputText>
        </h:column>
        <h:column>
           <s:button id="delete" value="Delete" action="#{messageManager.delete}"/>
        </h:column>
     </h:dataTable>
     <h3><h:outputText id="title" value="#{message.title}"/></h3>
     <div><h:outputText id="text" value="#{message.text}"/></div>
  </f:view>
 </h:body>
</html>

The first time we navigate to the messages.xhtml page, 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.

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.

The center of this example is the jBPM process definition. There are also two JSFs 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:


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


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

The JSF itself is trivial:


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


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 core of the application is in todo.xhtml:

Example 1.18. todo.xhtml


<?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.org/schema/seam/taglib"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
<head>
<title>Todo List</title>
</head>
<body>
<h1>Todo List</h1>
<f:view>
   <h:form id="list">
      <div>
         <h:outputText id="noItems" value="There are no todo items." rendered="#{empty taskInstancePriorityList}"/>
         <h:dataTable id="items" value="#{taskInstancePriorityList}" var="task" rendered="#{not empty taskInstancePriorityList}">
            <h:column>
                <f:facet name="header">
                    <h:outputText value="Description"/>
                </f:facet>
                <h:inputText id="description" value="#{task.description}" style="width: 400"/>
            </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 id="priority" value="#{task.priority}" style="width: 30"/>
            </h:column>
            <h:column>
                <f:facet name="header">
                    <h:outputText value="Due Date"/>
                </f:facet>
                <h:inputText id="dueDate" value="#{task.dueDate}" style="width: 100">
                    <f:convertDateTime type="date" dateStyle="short"/>
                </h:inputText>
            </h:column>
            <h:column>
                <s:button id="done" action="#{todoList.done}" taskInstance="#{task}" value="Done"/>
            </h:column>
         </h:dataTable>
      </div>
      <div>
      <h:messages/>
      </div>
      <div>
         <h:commandButton id="update" value="Update Items" rendered="#{not empty taskInstanceList}"/>
      </div>
   </h:form>
   <h:form id="new">
      <div>
         <h:inputText id="description" value="#{todoList.description}" style="width: 400"/>
         <h:commandButton id="create" value="Create New Item" action="#{todoList.createTodo}"/>
      </div>
   </h:form>
</f:view>
</body>
</html>

Let's take this one piece at a time.

The page renders a list of tasks, which it gets from a built-in Seam component named taskInstanceList. The list is defined inside a JSF form.


Each element of the list is an instance of the jBPM class TaskInstance. The following code simply displays the interesting properties of each task in the list. For the description, priority and due date, we use input controls, to allow the user to update these values.


<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"/>
    </f:facet>
    <h:inputText value="#{task.dueDate}" style="width: 100">
        <f:convertDateTime type="date" dateStyle="short"/>
    </h:inputText>
</h:column>

Note

Seam provides a default JSF date converter for converting a string to a date (no time). Thus, the converter is not necessary for the field bound to #{task.dueDate}.

This button ends the task by calling the action method annotated @StartTask @EndTask. It passes the task id to Seam as a request parameter:


<h:column>
    <s:button value="Done" action="#{todoList.done}" taskInstance="#{task}"/>
</h:column>

Note that this is using a Seam <s:button> JSF control from the seam-ui.jar package. This button is used to update the properties of the tasks. When the form is submitted, Seam and jBPM will make any changes to the tasks persistent. There is no need for any action listener method:


<h:commandButton value="Update Items" action="update"/>

A second form on the page is used to create new items, by calling the action method annotated @CreateProcess.


<h:form id="new">
    <div>
        <h:inputText value="#{todoList.description}"/>
        <h:commandButton value="Create New Item" action="#{todoList.createTodo}"/>
    </div>
</h:form>

After logging in, todo.xhtml uses the taskInstanceList component to display a table of outstanding todo items for a the current user. Initially there are none. It also presents a form to enter a new entry. When the user types the todo item and hits the "Create New Item" button, #{todoList.createTodo} is called. This starts the todo process, as defined in todo.jpdl.xml.

The process instance is created, starting in the start state and immediately transition to the todo state, where a new task is created. The task description is set based on the user's input, which was saved to #{todoList.description}. Then, the task is assigned to the current user, which was stored in the seam actor component. Note that in this example, the process has no extra process state. All the state in this example is stored in the task definition. The process and task information is stored in the database at the end of the request.

When todo.xhtml is redisplayed, taskInstanceList now finds the task that was just created. The task is shown in an h:dataTable. The internal state of the task is displayed in each column: #{task.description}, #{task.priority}, #{task.dueDate}, etc... These fields can all be edited and saved back to the database.

Each todo item also has "Done" button, which calls #{todoList.done}. The todoList component knows which task the button is for because each s:button specificies taskInstance="#{task}", referring to the task for that particular line of the table. The @StartTast and @EndTask annotations cause seam to make the task active and immediately complete the task. The original process then transitions into the done state, according to the process definition, where it ends. The state of the task and process are both updated in the database.

When todo.xhtml is displayed again, the now-completed task is no longer displayed in the taskInstanceList, since that component only display active tasks for the user.

For Seam applications with relatively freeform (ad hoc) navigation, JSF/Seam navigation rules are a perfectly good way to define the page flow. For applications with a more constrained style of navigation, especially for user interfaces which are more stateful, navigation rules make it difficult to really understand the flow of the system. To understand the flow, you need to piece it together from the view pages, the actions and the navigation rules.

Seam allows you to use a jPDL process definition to define pageflow. The simple number guessing example shows how this is done.

The example is implemented using one JavaBean, three JSF pages and a jPDL pageflow definition. Let's begin with the pageflow:

Example 1.20. pageflow.jpdl.xml

<pageflow-definition 
        xmlns="http://jboss.org/schema/seam/pageflow"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://jboss.org/schema/seam/pageflow 
                            http://jboss.org/schema/seam/pageflow-2.3.xsd"
        name="numberGuess">
   
   <start-page(1) name="displayGuess" view-id="/numberGuess.xhtml">
      <redirect/>
      <transit(2)ion name="guess" to="evaluateGuess">
         <acti(3)on expression="#{numberGuess.guess}"/>
      </transition>
      <transition name="giveup" to="giveup"/>
      <transition name="cheat" to="cheat"/>
   </start-page>
              (4)
   <decision name="evaluateGuess" expression="#{numberGuess.correctGuess}">
      <transition name="true" to="win"/>
      <transition name="false" to="evaluateRemainingGuesses"/>
   </decision>
   
   <decision name="evaluateRemainingGuesses" expression="#{numberGuess.lastGuess}">
      <transition name="true" to="lose"/>
      <transition name="false" to="displayGuess"/>
   </decision>
   
   <page name="giveup" view-id="/giveup.xhtml">
      <redirect/>
      <transition name="yes" to="lose"/>
      <transition name="no" to="displayGuess"/>
   </page>
   
   <process-state name="cheat">
      <sub-process name="cheat"/>
      <transition to="displayGuess"/>
   </process-state>
   
   <page name="win" view-id="/win.xhtml">
      <redirect/>
      <end-conversation/>
   </page>
   
   <page name="lose" view-id="/lose.xhtml">
      <redirect/>
      <end-conversation/>
   </page>
   
</pageflow-definition>

1

The <page> element defines a wait state where the system displays a particular JSF view and waits for user input. The view-id is the same JSF view id used in plain JSF navigation rules. The redirect attribute tells Seam to use post-then-redirect when navigating to the page. (This results in friendly browser URLs.)

2

The <transition> element names a JSF outcome. The transition is triggered when a JSF action results in that outcome. Execution will then proceed to the next node of the pageflow graph, after invocation of any jBPM transition actions.

3

A transition <action> is just like a JSF action, except that it occurs when a jBPM transition occurs. The transition action can invoke any Seam component.

4

A <decision> node branches the pageflow, and determines the next node to execute by evaluating a JSF EL expression.


Now that we have seen the pageflow, it is very, very easy to understand the rest of the application!

Here is the main page of the application, numberGuess.xhtml:

Example 1.21. numberGuess.xhtml


<!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:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:s="http://jboss.org/schema/seam/taglib">
  <h:head>
    <title>Guess a number...</title>
    <link href="niceforms.css" rel="stylesheet" type="text/css" />
    <script language="javascript" type="text/javascript" src="niceforms.js"><!-- --></script>
  </h:head>
  <h:body>
    <h1>Guess a number...</h1>
      <h:form id="NumberGuessMain" styleClass="niceform">

        <div>
        <h:messages id="messages" globalOnly="true"/>
        <h:outputText id="Higher"
                          value="Higher!" 
                      rendered="#{numberGuess.randomNumber gt numberGuess.currentGuess}"/>
        <h:outputText id="Lower"
                          value="Lower!" 
                      rendered="#{numberGuess.randomNumber lt numberGuess.currentGuess}"/>
        </div>

        <div>
        I'm thinking of a number between <h:outputText id="Smallest" value="#{numberGuess.smallest}"/> and
        <h:outputText id="Biggest" value="#{numberGuess.biggest}"/>. You have
        <h:outputText id="RemainingGuesses" value="#{numberGuess.remainingGuesses}"/> guesses.
        </div>

        <div>
        Your guess:
        <h:inputText id="inputGuess" value="#{numberGuess.currentGuess}" required="true" size="3" 
                 rendered="#{(numberGuess.biggest-numberGuess.smallest) gt 20}">
          <f:validateLongRange maximum="#{numberGuess.biggest}" 
                               minimum="#{numberGuess.smallest}"/>
        </h:inputText>
        <h:selectOneMenu id="selectGuessMenu" value="#{numberGuess.currentGuess}" required="true"
                       rendered="#{(numberGuess.biggest-numberGuess.smallest) le 20 and (numberGuess.biggest-numberGuess.smallest) gt 4}">
          <s:selectItems id="PossibilitiesMenuItems" value="#{numberGuess.possibilities}" var="i" label="#{i}"/>
        </h:selectOneMenu>
        <h:selectOneRadio id="selectGuessRadio" value="#{numberGuess.currentGuess}" required="true"
                       rendered="#{(numberGuess.biggest-numberGuess.smallest) le 4}">
          <s:selectItems id="PossibilitiesRadioItems" value="#{numberGuess.possibilities}" var="i" label="#{i}"/>
        </h:selectOneRadio>
        <h:commandButton id="GuessButton" value="Guess" action="guess"/>
        <s:button id="CheatButton" value="Cheat" action="cheat"/>
        <s:button id="GiveUpButton" value="Give up" action="giveup"/>
        </div>

        <div>
        <h:message id="message" for="inputGuess" style="color: red"/>
        </div>

      </h:form>
  </h:body>
</html>

Notice how the command button names the guess transition instead of calling an action directly.

The win.xhtml page is predictable:


The lose.xhtml looks roughly the same, so we'll skip over it.

Finally, we'll look at the actual application code:

Example 1.23. NumberGuess.java

@Name("numberGuess")

@Scope(ScopeType.CONVERSATION)
public class NumberGuess implements Serializable {
   
   private int randomNumber;
   private Integer currentGuess;
   private int biggest;
   private int smallest;
   private int guessCount;
   private int maxGuesses;
   private boolean cheated;
   
(1)   @Create
   public void begin()
   {
      randomNumber = new Random().nextInt(100);
      guessCount = 0;
      biggest = 100;
      smallest = 1;
   }
   
   public void setCurrentGuess(Integer guess)
   {
      this.currentGuess = guess;
   }
   
   public Integer getCurrentGuess()
   {
      return currentGuess;
   }
   
   public void guess()
   {
      if (currentGuess>randomNumber)
      {
         biggest = currentGuess - 1;
      }
      if (currentGuess<randomNumber)
      {
         smallest = currentGuess + 1;
      }
      guessCount ++;
   }
   
   public boolean isCorrectGuess()
   {
      return currentGuess==randomNumber;
   }
   
   public int getBiggest()
   {
      return biggest;
   }
   
   public int getSmallest()
   {
      return smallest;
   }
   
   public int getGuessCount()
   {
      return guessCount;
   }
   
   public boolean isLastGuess()
   {
      return guessCount==maxGuesses;
   }
   public int getRemainingGuesses() {
      return maxGuesses-guessCount;
   }
   public void setMaxGuesses(int maxGuesses) {
      this.maxGuesses = maxGuesses;
   }
   public int getMaxGuesses() {
      return maxGuesses;
   }
   public int getRandomNumber() {
      return randomNumber;
   }
   public void cheated()
   {
      cheated = true;
   }
   
   public boolean isCheat() {
      return cheated;
   }
   
   public List<Integer> getPossibilities()
   {
      List<Integer> result = new ArrayList<Integer>();
      for(int i=smallest; i<=biggest; i++) result.add(i);
      return result;
   }
   
}

1

The first time a JSF page asks for a numberGuess component, Seam will create a new one for it, and the @Create method will be invoked, allowing the component to initialize itself.


The pages.xml file starts a Seam conversation (much more about that later), and specifies the pageflow definition to use for the conversation's page flow.


As you can see, this Seam component is pure business logic! It doesn't need to know anything at all about the user interaction flow. This makes the component potentially more reuseable.

We'll step through basic flow of the application. The game starts with the numberGuess.xhtml view. When the page is first displayed, the pages.xml configuration causes conversation to begin and associates the numberGuess pageflow with that conversation. The pageflow starts with a start-page tag, which is a wait state, so the numberGuess.xhtml is rendered.

The view references the numberGuess component, causing a new instance to be created and stored in the conversation. The @Create method is called, initializing the state of the game. The view displays an h:form that allows the user to edit #{numberGuess.currentGuess}.

The "Guess" button triggers the guess action. Seam defers to the pageflow to handle the action, which says that the pageflow should transition to the evaluateGuess state, first invoking #{numberGuess.guess}, which updates the guess count and highest/lowest suggestions in the numberGuess component.

The evaluateGuess state checks the value of #{numberGuess.correctGuess} and transitions either to the win or evaluatingRemainingGuesses state. We'll assume the number was incorrect, in which case the pageflow transitions to evaluatingRemainingGuesses. That is also a decision state, which tests the #{numberGuess.lastGuess} state to determine whether or not the user has more guesses. If there are more guesses (lastGuess is false), we transition back to the original displayGuess state. Finally we've reached a page state, so the associated page /numberGuess.xhtml is displayed. Since the page has a redirect element, Seam sends a redirect to the user's browser, starting the process over.

We won't follow the state any more except to note that if on a future request either the win or the lose transition were taken, the user would be taken to either the /win.xhtml or /lose.xhtml. Both states specify that Seam should end the conversation, tossing away all the game state and pageflow state, before redirecting the user to the final page.

The numberguess example also contains Giveup and Cheat buttons. You should be able to trace the pageflow state for both actions relatively easily. Pay particular attention to the cheat transition, which loads a sub-process to handle that flow. Although it's overkill for this application, it does demonstrate how complex pageflows can be broken down into smaller parts to make them easier to understand.

The project structure is identical to the previous one, to install and deploy this application, please refer to Section 1.1, “Using the Seam examples”. Once you've successfully started the application, you can access it by pointing your browser to http://localhost:8080/seam-booking/

The application uses six session beans for to implement the business logic for the listed features.

  • AuthenticatorAction provides the login authentication logic.

  • BookingListAction retrieves existing bookings for the currently logged in user.

  • ChangePasswordAction updates the password of the currently logged in user.

  • HotelBookingAction implements booking and confirmation functionality. This functionality is implemented as a conversation, so this is one of the most interesting classes in the application.

  • HotelSearchingAction implements the hotel search functionality.

  • RegisterAction registers a new system user.

Three entity beans implement the application's persistent domain model.

  • Hotel is an entity bean that represent a hotel

  • Booking is an entity bean that represents an existing booking

  • User is an entity bean to represents a user who can make hotel bookings

We encourage you browse the sourcecode at your pleasure. In this tutorial we'll concentrate upon one particular piece of functionality: hotel search, selection, booking and confirmation. From the point of view of the user, everything from selecting a hotel to confirming a booking is one continuous unit of work, a conversation. Searching, however, is not part of the conversation. The user can select multiple hotels from the same search results page, in different browser tabs.

Most web application architectures have no first class construct to represent a conversation. This causes enormous problems managing conversational state. Usually, Java web applications use a combination of several techniques. Some state can be transfered in the URL. What can't is either thrown into the HttpSession or flushed to the database after every request, and reconstructed from the database at the beginning of each new request.

Since the database is the least scalable tier, this often results in an utterly unacceptable lack of scalability. Added latency is also a problem, due to the extra traffic to and from the database on every request. To reduce this redundant traffic, Java applications often introduce a data (second-level) cache that keeps commonly accessed data between requests. This cache is necessarily inefficient, because invalidation is based upon an LRU policy instead of being based upon when the user has finished working with the data. Furthermore, because the cache is shared between many concurrent transactions, we've introduced a whole raft of problem's associated with keeping the cached state consistent with the database.

Now consider the state held in the HttpSession. The HttpSession is great place for true session data, data that is common to all requests that the user has with the application. However, it's a bad place to store data related to individual series of requests. Using the session of conversational quickly breaks down when dealing with the back button and multiple windows. On top of that, without careful programming, data in the HTTP Session can grow quite large, making the HTTP session difficult to cluster. Developing mechanisms to isolate session state associated with different concurrent conversations, and incorporating failsafes to ensure that conversation state is destroyed when the user aborts one of the conversations by closing a browser window or tab is not for the faint hearted. Fortunately, with Seam, you don't have to worry about that.

Seam introduces the conversation context as a first class construct. You can safely keep conversational state in this context, and be assured that it will have a well-defined lifecycle. Even better, you won't need to be continually pushing data back and forth between the application server and the database, since the conversation context is a natural cache of data that the user is currently working with.

In this application, we'll use the conversation context to store stateful session beans. There is an ancient canard in the Java community that stateful session beans are a scalability killer. This may have been true in the early days of enterprise Java, but it is no longer true today. Modern application servers have extremely sophisticated mechanisms for stateful session bean state replication. JBoss AS, for example, performs fine-grained replication, replicating only those bean attribute values which actually changed. Note that all the traditional technical arguments for why stateful beans are inefficient apply equally to the HttpSession, so the practice of shifting state from business tier stateful session bean components to the web session to try and improve performance is unbelievably misguided. It is certainly possible to write unscalable applications using stateful session beans, by using stateful beans incorrectly, or by using them for the wrong thing. But that doesn't mean you should never use them. If you remain unconvinced, Seam allows the use of POJOs instead of stateful session beans. With Seam, the choice is yours.

The booking example application shows how stateful components with different scopes can collaborate together to achieve complex behaviors. The main page of the booking application allows the user to search for hotels. The search results are kept in the Seam session scope. When the user navigates to one of these hotels, a conversation begins, and a conversation scoped component calls back to the session scoped component to retrieve the selected hotel.

The booking example also demonstrates the use of RichFaces Ajax to implement rich client behavior without the use of handwritten JavaScript.

The search functionality is implemented using a session-scope stateful session bean, similar to the one we saw in the message list example.

Example 1.25. HotelSearchingAction.java

(1)@Stateful

@Name("hotelSearch")
@Scope(ScopeType.SESSION)
(2)@Restrict("#{identity.loggedIn}")
public class HotelSearchingAction implements HotelSearching
{
   
   @PersistenceContext
   private EntityManager em;
   
   private String searchString;
   private int pageSize = 10;
   private int page;
   
(3)   @DataModel
   private List<Hotel> hotels;
   
   public void find()
   {
      page = 0;
      queryHotels();
   }
   public void nextPage()
   {
      page++;
      queryHotels();
   }
      
   private void queryHotels()
   {
      hotels = 
          em.createQuery("select h from Hotel h where lower(h.name) like #{pattern} " + 
                         "or lower(h.city) like #{pattern} " + 
                         "or lower(h.zip) like #{pattern} " +
                         "or lower(h.address) like #{pattern}")
            .setMaxResults(pageSize)
            .setFirstResult( page * pageSize )
            .getResultList();
   }
   
   public boolean isNextPageAvailable()
   {
      return hotels!=null && hotels.size()==pageSize;
   }
   
   public int getPageSize() {
      return pageSize;
   }
   
   public void setPageSize(int pageSize) {
      this.pageSize = pageSize;
   }
   
   @Factory(value="pattern", scope=ScopeType.EVENT)
   public String getSearchPattern()
   {
      return searchString==null ? 
            "%" : '%' + searchString.toLowerCase().replace('*', '%') + '%';
   }
   
   public String getSearchString()
   {
      return searchString;
   }
   
   public void setSearchString(String searchString)
   {
      this.searchString = searchString;
   }
(4)   
   @Remove
   public void destroy() {}
}

1

The EJB standard @Stateful annotation identifies this class as a stateful session bean. Stateful session beans are scoped to the conversation context by default.

2

The @Restrict annotation applies a security restriction to the component. It restricts access to the component allowing only logged-in users. The security chapter explains more about security in Seam.

3

The @DataModel annotation exposes a List as a JSF ListDataModel. This makes it easy to implement clickable lists for search screens. In this case, the list of hotels is exposed to the page as a ListDataModel in the conversation variable named hotels.

4

The EJB standard @Remove annotation specifies that a stateful session bean should be removed and its state destroyed after invocation of the annotated method. In Seam, all stateful session beans must define a method with no parameters marked @Remove. This method will be called when Seam destroys the session context.


The main page of the application is a Facelets page. Let's look at the fragment which relates to searching for hotels:

Example 1.26. main.xhtml

<div class="section">
  
    <span class="errors">
       <h:messages id="messages" globalOnly="true"/>
    </span>
    
    <h1>Search Hotels</h1>

    <h:form id="searchCriteria">
    <fieldset>
       <h:inputText id="searchString" value="#{hotelSearch.searchString}" style="width: 165px;">
        <a:ajax event="keyup" render="searchResults" listener="#{hotelSearch.find}"/>
       </h:inp(1)utText>                     
       &#160;
       <a:commandButton id="findHotels" value="Find Hotels" actionListener="#{hotelSearch.find}"  render="searchResults"/>
       &#160;
       <a:status id="status">
          <f:facet id="StartStatus" name="start">
             <(2)h:graphicImage id="SpinnerGif" value="/img/spinner.gif"/>
          </f:facet>
       </a:status>
       <br/>
       <h:outputLabel id="MaximumResultsLabel" for="pageSize">Maximum results:</h:outputLabel>&#160;
       <h:selectOneMenu id="pageSize" value="#{hotelSearch.pageSize}">
          <f:selectItem id="PageSize5" itemLabel="5" itemValue="5"/>
          <f:selectItem id="PageSize10" itemLabel="10" itemValue="10"/>
          <f:selectItem id="PageSize20" itemLabel="20" itemValue="20"/>
       </h:selectOneMenu>
    </fieldset>
    </h:form>
    
</div>

<a:outputPanel id="searchResults">
  <div class="section">
    <h:outputT(3)ext id="NoHotelsFoundMessage" value="No Hotels Found" rendered="#{hotels != null and hotels.rowCount==0}"/>
    <h:dataTable id="hotels" value="#{hotels}" var="hot" rendered="#{hotels.rowCount>0}">
        <h:column id="column1">
            <f:facet id="NameFacet" name="header">Name</f:facet>
            #{hot.name}
        </h:column>
        <h:column id="column2">
            <f:facet id="AddressFacet" name="header">Address</f:facet>
            #{hot.address}
        </h:column>
        <h:column id="column3">
            <f:facet id="CityStateFacet" name="header">City, State</f:facet>
            #{hot.city}, #{hot.state}, #{hot.country}
        </h:column> 
        <h:column id="column4">
            <f:facet id="ZipFacet" name="header">Zip</f:facet>
            #{hot.zip}
        </h:column>
        <h:column id="column5">
            <f:facet id="ActionFacet" name="header">Action</f:facet>
            <s:link id="viewHotel" value="View Hotel" action="#{hotelBooking.selectHotel(hot)}"/>
        </h:column>
    </h:dataTable>
    <s:link id="MoreResultsLink" value="More results" action="#{hotelSearch.nextPage}" rendered="#{hotelSearch.nextPageAvailable}"/>
  </div>      (4)
</a:outputPanel>

1

The RichFaces <a:ajax> tag allows a JSF action event listener to be called by asynchronous XMLHttpRequest when a JavaScript event like onkeyup occurs. Even better, the render attribute lets us render a fragment of the JSF page and perform a partial page update when the asynchronous response is received.

2

The RichFaces <a:status> tag lets us display an animated image while we wait for asynchronous requests to return.

3

The RichFaces <a:outputPanel> tag defines a region of the page which can be re-rendered by an asynchronous request.

4

The Seam <s:link> tag lets us attach a JSF action listener to an ordinary (non-JavaScript) HTML link. The advantage of this over the standard JSF <h:commandLink> is that it preserves the operation of "open in new window" and "open in new tab".

If you're wondering how navigation occurs, you can find all the rules in WEB-INF/pages.xml; this is discussed in Section 7.7, “Navigation”.


This page displays the search results dynamically as we type, and lets us choose a hotel and pass it to the selectHotel() method of the HotelBookingAction, which is where the really interesting stuff is going to happen.

Now let's see how the booking example application uses a conversation-scoped stateful session bean to achieve a natural cache of persistent data related to the conversation. The following code example is pretty long. But if you think of it as a list of scripted actions that implement the various steps of the conversation, it's understandable. Read the class from top to bottom, as if it were a story.

Example 1.27. HotelBookingAction.java

@Stateful

@Name("hotelBooking")
@Restrict("#{identity.loggedIn}")
public class HotelBookingAction implements HotelBooking
{
   
(1)   @PersistenceContext(type=EXTENDED)
   private EntityManager em;
   
   @In 
   private User user;
   
   @In(required=false) @Out
   private Hotel hotel;
   
   @In(required=false) 
(2)   @Out(required=false)
   private Booking booking;
     
   @In
   private FacesMessages facesMessages;
      
   @In
   private Events events;
   
   @Logger 
   private Log log;
   
   private boolean bookingValid;
   
(3)   @Begin
   public void selectHotel(Hotel selectedHotel)
   {
      hotel = em.merge(selectedHotel);
   }
   
   public void bookHotel()
   {      
      booking = new Booking(hotel, user);
      Calendar calendar = Calendar.getInstance();
      booking.setCheckinDate( calendar.getTime() );
      calendar.add(Calendar.DAY_OF_MONTH, 1);
      booking.setCheckoutDate( calendar.getTime() );
   }
   
   public void setBookingDetails()
   {
      Calendar calendar = Calendar.getInstance();
      calendar.add(Calendar.DAY_OF_MONTH, -1);
      if ( booking.getCheckinDate().before( calendar.getTime() ) )
      {
         facesMessages.addToControl("checkinDate", "Check in date must be a future date");
         bookingValid=false;
      }
      else if ( !booking.getCheckinDate().before( booking.getCheckoutDate() ) )
      {
         facesMessages.addToControl("checkoutDate", 
                                    "Check out date must be later than check in date");
         bookingValid=false;
      }
      else
      {
         bookingValid=true;
      }
   }
   
   public boolean isBookingValid()
   {
      return bookingValid;
   }
   
(4)   @End
   public void confirm()
   {
      em.persist(booking);
      facesMessages.add("Thank you, #{user.name}, your confimation number " + 
                        " for #{hotel.name} is #{booki g.id}");
      log.info("New booking: #{booking.id} for #{user.username}");
      events.raiseTransactionSuccessEvent("bookingConfirmed");
   }
   
   @End
   public void cancel() {}
   
(5)   @Remove
   public void destroy() {}

1

This bean uses an EJB3 extended persistence context, so that any entity instances remain managed for the whole lifecycle of the stateful session bean.

2

The @Out annotation declares that an attribute value is outjected to a context variable after method invocations. In this case, the context variable named hotel will be set to the value of the hotel instance variable after every action listener invocation completes.

3

The @Begin annotation specifies that the annotated method begins a long-running conversation, so the current conversation context will not be destroyed at the end of the request. Instead, it will be reassociated with every request from the current window, and destroyed either by timeout due to conversation inactivity or invocation of a matching @End method.

4

The @End annotation specifies that the annotated method ends the current long-running conversation, so the current conversation context will be destroyed at the end of the request.

5

This EJB remove method will be called when Seam destroys the conversation context. Don't forget to define this method!


HotelBookingAction contains all the action listener methods that implement selection, booking and booking confirmation, and holds state related to this work in its instance variables. We think you'll agree that this code is much cleaner and simpler than getting and setting HttpSession attributes.

Even better, a user can have multiple isolated conversations per login session. Try it! Log in, run a search, and navigate to different hotel pages in multiple browser tabs. You'll be able to work on creating two different hotel reservations at the same time. If you leave any one conversation inactive for long enough, Seam will eventually time out that conversation and destroy its state. If, after ending a conversation, you backbutton to a page of that conversation and try to perform an action, Seam will detect that the conversation was already ended, and redirect you to the search page.

Long-running conversations make it simple to maintain consistency of state in an application even in the face of multi-window operation and back-buttoning. Unfortunately, simply beginning and ending a long-running conversation is not always enough. Depending on the requirements of the application, inconsistencies between what the user's expectations and the reality of the application’s state can still result.

The nested booking application extends the features of the hotel booking application to incorporate the selection of rooms. Each hotel has available rooms with descriptions for a user to select from. This requires the addition of a room selection page in the hotel reservation flow.

The user now has the option to select any available room to be included in the booking. As with the hotel booking application we saw previously, this can lead to issues with state consistency. As with storing state in the HTTPSession, if a conversation variable changes it affects all windows operating within the same conversation context.

To demonstrate this, let’s suppose the user clones the room selection screen in a new window. The user then selects the Wonderful Room and proceeds to the confirmation screen. To see just how much it would cost to live the high-life, the user returns to the original window, selects the Fantastic Suite for booking, and again proceeds to confirmation. After reviewing the total cost, the user decides that practicality wins out and returns to the window showing Wonderful Room to confirm.

In this scenario, if we simply store all state in the conversation, we are not protected from multi-window operation within the same conversation. Nested conversations allow us to achieve correct behavior even when context can vary within the same conversation.

Now let's see how the nested booking example extends the behavior of the hotel booking application through use of nested conversations. Again, we can read the class from top to bottom, as if it were a story.

Example 1.28. RoomPreferenceAction.java

@Stateful

@Name("roomPreference")
@Restrict("#{identity.loggedIn}")
public class RoomPreferenceAction implements RoomPreference 
{
   @Logger 
   private Log log;
   @In private Hotel hotel;
   
   @In private Booking booking;
   @DataModel(value="availableRooms")
   private List<Room> availableRooms;
   @DataModelSelection(value="availableRooms")
   private Room roomSelection;
    
   @In(required=false, value="roomSelection")
   @Out(required=false, value="roomSelection")
   private Room room;
   @Factory("availableRooms")
(1)   public void loadAvailableRooms()
   {
      availableRooms = hotel.getAvailableRooms(booking.getCheckinDate(), booking.getCheckoutDate());
      log.info("Retrieved #0 available rooms", availableRooms.size());
   }
   public BigDecimal getExpectedPrice()
   {
      log.info("Retrieving price for room #0", roomSelection.getName());
      
      return booking.getTotal(roomSelection);
   }
(2)   @Begin(nested=true)
   public String selectPreference()
   {
      log.info("Room selected");
      
(3)      this.room = this.roomSelection;
      
      return "payment";
   }
   public String requestConfirmation()
   {
      // all validations are performed through the s:validateAll, so checks are already
      // performed
      log.info("Request confirmation from user");
      
      return "confirm";
   }
   @End(beforeRedirect=true)
(4)   public String cancel()
   {
      log.info("ending conversation");
      return "cancel";
   }
   @Destroy @Remove                                                                      
   public void destroy() {}    
}

1

The hotel instance is injected from the conversation context. The hotel is loaded through an extended persistence context so that the entity remains managed throughout the conversation. This allows us to lazily load the availableRooms through an @Factory method by simply walking the association.

2

When @Begin(nested=true) is encountered, a nested conversation is pushed onto the conversation stack. When executing within a nested conversation, components still have access to all outer conversation state, but setting any values in the nested conversation’s state container does not affect the outer conversation. In addition, nested conversations can exist concurrently stacked on the same outer conversation, allowing independent state for each.

3

The roomSelection is outjected to the conversation based on the @DataModelSelection. Note that because the nested conversation has an independent context, the roomSelection is only set into the new nested conversation. Should the user select a different preference in another window or tab a new nested conversation would be started.

4

The @End annotation pops the conversation stack and resumes the outer conversation. The roomSelection is destroyed along with the conversation context.


When we begin a nested conversation it is pushed onto the conversation stack. In the nestedbooking example, the conversation stack consists of the outer long-running conversation (the booking) and each of the nested conversations (room selections).

Example 1.29. rooms.xhtml

<div class="section">
  <h1>Room Preference</h1>
</div>
<div class="section">
  <h:form id="room_selections_form">
    <div class="section">
        <h:outputText styleClass="output" value="No rooms available for the dates selected: " rendered="#{availableRooms != null and availableRooms.rowCount == 0}"/>
        <h:outputText styleClass="output" value="Rooms available for the dates selected: " rendered="#{availableRooms != null and availableRooms.rowCount > 0}"/>
        <h:outputText styleClass="output" value="#{booking.checkinDate}"/> -
        <h:outputText styleClass="output" value="#{booking.checkoutDate}"/>
            
        <h:dat(1)aTable id="rooms" value="#{availableRooms}" var="room" rendered="#{availableRooms.rowCount &gt; 0}">
            <h:column>
              <f:facet name="header">Name</f:facet>
              #{room.name}
            </h:column>
            <h:column>
              <f:facet name="header">Description</f:facet>
              #{room.description}
            </h:column>
            <h:column>
              <f:facet name="header">Per Night</f:facet>
              <h:outputText value="#{room.price}">
                <f:convertNumber type="currency" currencySymbol="$"/>
              </h:outputText>
            </h:column>
            <h:column>
              <f:facet name="header">Action</f:facet>
              (2)<h:commandLink id="selectRoomPreference" action="#{roomPreference.selectPreference}">Select</h:commandLink>
            </h:column>
        </h:dataTable>
      </div>
      <div class="entry">
        <div class="label">&#160;</div>
        <div class="input">
          <s:b(3)utton id="cancel" value="Revise Dates" view="/book.xhtml"/>
        </div>
      </div>  
    </h:form>
</div>

1

When requested from EL, the #{availableRooms} are loaded by the @Factory method defined in RoomPreferenceAction. The @Factory method will only be executed once to load the values into the current context as a @DataModel instance.

2

Invoking the #{roomPreference.selectPreference} action results in the row being selected and set into the @DataModelSelection. This value is then outjected to the nested conversation context.

3

Revising the dates simply returns to the /book.xhtml. Note that we have not yet nested a conversation (no room preference has been selected), so the current conversation can simply be resumed. The <s:button> component simply propagates the current conversation when displaying the /book.xhtml view.


Now that we have seen how to nest a conversation, let's see how we can confirm the booking once a room has been selected. This can be achieved by simply extending the behavior of the HotelBookingAction.

Example 1.30. HotelBookingAction.java

@Stateful

@Name("hotelBooking")
@Restrict("#{identity.loggedIn}")
public class HotelBookingAction implements HotelBooking
{
   
   @PersistenceContext(type=EXTENDED)
   private EntityManager em;
   
   @In 
   private User user;
   
   @In(required=false) @Out
   private Hotel hotel;
   
   @In(required=false) 
   @Out(required=false)
   private Booking booking;
   
   @In(required=false)
   private Room roomSelection;
   
   @In
   private FacesMessages facesMessages;
      
   @In
   private Events events;
   
   @Logger 
   private Log log;
   
   @Begin
   public void selectHotel(Hotel selectedHotel)
   {
      log.info("Selected hotel #0", selectedHotel.getName());
      hotel = em.merge(selectedHotel);
   }
   
   public String setBookingDates()
   {
      // the result will indicate whether or not to begin the nested conversation
      // as well as the navigation.  if a null result is returned, the nested
      // conversation will not begin, and the user will be returned to the current
      // page to fix validation issues
      String result = null;
      Calendar calendar = Calendar.getInstance();
      calendar.add(Calendar.DAY_OF_MONTH, -1);
      // validate what we have received from the user so far
      if ( booking.getCheckinDate().before( calendar.getTime() ) )
      {
         facesMessages.addToControl("checkinDate", "Check in date must be a future date");
      }
      else if ( !booking.getCheckinDate().before( booking.getCheckoutDate() ) )
      {
         facesMessages.addToControl("checkoutDate", "Check out date must be later than check in date");
      }
      else
      {
         result = "rooms";
      }
      return result;
   }
   
   public void bookHotel()
   {      
      booking = new Booking(hotel, user);
      Calendar calendar = Calendar.getInstance();
      booking.setCheckinDate( calendar.getTime() );
      calendar.add(Calendar.DAY_OF_MONTH, 1);
      booking.setCheckoutDate( calendar.getTime() );
   }
   
   @End(root=true)
(1)   public void confirm()
   {
      // on confirmation we set the room preference in the booking.  the room preference
      // will be injected based on the nested conversation we are in.
      booking.setRoomPreference(roomSelection); (2)
      em.persist(booking);
      facesMessages.add("Thank you, #{user.name}, your confimation number for #{hotel.name} is #{booking.id}");
      log.info("New booking: #{booking.id} for #{user.username}");
      events.raiseTransactionSuccessEvent("bookingConfirmed");
   }
   
(3)   @End(root=true, beforeRedirect=true)
   public void cancel() {}
   
   @Destroy @Remove
   public void destroy() {}
}

1

Annotating an action with @End(root=true) ends the root conversation which effectively destroys the entire conversation stack. When any conversation is ended, its nested conversations are ended as well. As the root is the conversation that started it all, this is a simple way to destroy and release all state associated with a workspace once the booking is confirmed.

2

The roomSelection is only associated with the booking on user confirmation. While outjecting values to the nested conversation context will not impact the outer conversation, any objects injected from the outer conversation are injected by reference. This means that any changing to these objects will be reflected in the parent conversation as well as other concurrent nested conversations.

3

By simply annotating the cancellation action with @End(root=true, beforeRedirect=true) we can easily destroy and release all state associated with the workspace prior to redirecting the user back to the hotel selection view.


Feel free to deploy the application, open many windows or tabs and attempt combinations of various hotels with various room preferences. Confirming a booking always results in the correct hotel and room preference thanks to the nested conversation model.

Seam makes it very easy to implement applications which keep state on the server-side. However, server-side state is not always appropriate, especially in for functionality that serves up content. For this kind of problem we often want to keep application state in the URL so that any page can be accessed at any time through a bookmark. The blog example shows how to a implement an application that supports bookmarking throughout, even on the search results page. This example demonstrates how Seam can manage application state in the URL as well as how Seam can rewrite those URLs to be even

The Blog example demonstrates the use of "pull"-style MVC, where instead of using action listener methods to retrieve data and prepare the data for the view, the view pulls data from components as it is being rendered.

This snippet from the index.xhtml facelets page displays a list of recent blog entries:


If we navigate to this page from a bookmark, how does the #{blog.recentBlogEntries} data used by the <h:dataTable> actually get initialized? The Blog is retrieved lazily — "pulled" — when needed, by a Seam component named blog. This is the opposite flow of control to what is used in traditional action-based web frameworks like Struts.


This is good so far, but what about bookmarking the result of form submissions, such as a search results page?

The blog example has a tiny form in the top right of each page that allows the user to search for blog entries. This is defined in a file, menu.xhtml, included by the facelets template, template.xhtml:


Then the form would have looked like this:


<div id="search">
   <h:form>
      <h:inputText value="#{searchAction.searchPattern}"/>
      <h:commandButton value="Search" action="searchResults"/>
   </h:form>
</div>

But when we redirect, we need to include the values submitted with the form in the URL to get a bookmarkable URL like http://localhost:8080/seam-blog/search/. JSF does not provide an easy way to do this, but Seam does. We use two Seam features to accomplish this: page parameters and URL rewriting. Both are defined in WEB-INF/pages.xml:


The page parameter instructs Seam to link the request parameter named searchPattern to the value of #{searchService.searchPattern}, both whenever a request for the Search page comes in and whenever a link to the search page is generated. Seam takes responsibility for maintaining the link between URL state and application state, and you, the developer, don't have to worry about it.

Without URL rewriting, the URL for a search on the term book would be http://localhost:8080/seam-blog/seam/search.xhtml?searchPattern=book. This is nice, but Seam can make the URL even simpler using a rewrite rule. The first rewrite rule, for the pattern /search/{searchPattern}, says that any time we have a URL for search.xhtml with a searchPattern request parameter, we can fold that URL into the simpler URL. So,the URL we saw earlier, http://localhost:8080/seam-blog/seam/search.xhtml?searchPattern=book can be written instead as http://localhost:8080/seam-blog/search/book.

Just like with page parameters, URL rewriting is bi-directional. That means that Seam forwards requests for the simpler URL to the right view, and it also automatically generates the simpler view for you. You never need to worry about constructing URLs. It's all handled transparently behind the scenes. The only requirement is that to use URL rewriting, the rewrite filter needs to be enabled in components.xml.

<web:rewrite-filter view-mapping="/seam/*" />

The redirect takes us to the search.xhtml page:


<h:dataTable value="#{searchResults}" var="blogEntry">
  <h:column>
     <div>
        <s:link view="/entry.xhtml" propagation="none" value="#{blogEntry.title}">
           <f:param name="blogEntryId" value="#{blogEntry.id}"/>
        </s:link>
        posted on 
        <h:outputText value="#{blogEntry.date}">
            <f:convertDateTime timeZone="#{blog.timeZone}" locale="#{blog.locale}" type="both"/>
        </h:outputText>
     </div>
  </h:column>
</h:dataTable>

Which again uses "pull"-style MVC to retrieve the actual search results using Hibernate Search.

@Name("searchService")

public class SearchService 
{
   
   @In
   private FullTextEntityManager entityManager;
   
   private String searchPattern;
   
   @Factory("searchResults")
   public List<BlogEntry> getSearchResults()
   {
      if (searchPattern==null || "".equals(searchPattern) ) {
         searchPattern = null;
         return entityManager.createQuery("select be from BlogEntry be order by date desc").getResultList();
      }
      else
      {
         Map<String,Float> boostPerField = new HashMap<String,Float>();
         boostPerField.put( "title", 4f );
         boostPerField.put( "body", 1f );
         String[] productFields = {"title", "body"};
         QueryParser parser = new MultiFieldQueryParser(productFields, new StandardAnalyzer(), boostPerField);
         parser.setAllowLeadingWildcard(true);
         org.apache.lucene.search.Query luceneQuery;
         try
         {
            luceneQuery = parser.parse(searchPattern);
         }
         catch (ParseException e)
         {
            return null;
         }
         return entityManager.createFullTextQuery(luceneQuery, BlogEntry.class)
               .setMaxResults(100)
               .getResultList();
      }
   }
   public String getSearchPattern()
   {
      return searchPattern;
   }
   public void setSearchPattern(String searchPattern)
   {
      this.searchPattern = searchPattern;
   }
}

Very occasionally, it makes more sense to use push-style MVC for processing RESTful pages, and so Seam provides the notion of a page action. The Blog example uses a page action for the blog entry page, entry.xhtml. Note that this is a little bit contrived, it would have been easier to use pull-style MVC here as well.

The entryAction component works much like an action class in a traditional push-MVC action-oriented framework like Struts:

@Name("entryAction")

@Scope(STATELESS)
public class EntryAction
{
   @In Blog blog;
   
   @Out BlogEntry blogEntry;
   
   public void loadBlogEntry(String id) throws EntryNotFoundException
   {
      blogEntry = blog.getBlogEntry(id);
      if (blogEntry==null) throw new EntryNotFoundException(id);
   }
   
}

Page actions are also declared in pages.xml:


<pages>
   ...

    <page view-id="/entry.xhtml"> 
        <rewrite pattern="/entry/{blogEntryId}" />
        <rewrite pattern="/entry" />
        
        <param name="blogEntryId" 
               value="#{blogEntry.id}"/>
        
        <action execute="#{entryAction.loadBlogEntry(blogEntry.id)}"/>
    </page>
    
    <page view-id="/post.xhtml" login-required="true">
        <rewrite pattern="/post" />
        
        <action execute="#{postAction.post}"
                if="#{validation.succeeded}"/>
        
        <action execute="#{postAction.invalid}"
                if="#{validation.failed}"/>
        
        <navigation from-action="#{postAction.post}">
            <redirect view-id="/index.xhtml"/>
        </navigation>
    </page>

    <page view-id="*">
        <action execute="#{blog.hitCount.hit}"/>
    </page>

</pages>

Notice that the example is using page actions for post validation and the pageview counter. Also notice the use of a parameter in the page action method binding. This was not a standard feature of JSF EL in Java EE 5, but now it is and works like Seam lets you use it before, not just for page actions but also in JSF method bindings.

When the entry.xhtml page is requested, Seam first binds the page parameter blogEntryId to the model. Keep in mind that because of the URL rewriting, the blogEntryId parameter name won't show up in the URL. Seam then runs the page action, which retrieves the needed data — the blogEntry — and places it in the Seam event context. Finally, the following is rendered:


<div class="blogEntry">
    <h3>#{blogEntry.title}</h3>
    <div>
        <s:formattedText value="#{blogEntry.body}"/>
    </div>
    <p>
    [Posted on&#160;
    <h:outputText value="#{blogEntry.date}">
       <f:convertDateTime timeZone="#{blog.timeZone}" locale="#{blog.locale}" type="both"/>
    </h:outputText>]
    </p>
</div>

If the blog entry is not found in the database, the EntryNotFoundException exception is thrown. We want this exception to result in a 404 error, not a 505, so we annotate the exception class:

@ApplicationException(rollback=true)

@HttpError(errorCode=HttpServletResponse.SC_NOT_FOUND)
public class EntryNotFoundException extends Exception
{
   EntryNotFoundException(String id)
   {
      super("entry not found: " + id);
   }
}

An alternative implementation of the example does not use the parameter in the method binding:

@Name("entryAction")

@Scope(STATELESS)
public class EntryAction
{
   @In(create=true) 
   private Blog blog;
   
   @In @Out
   private BlogEntry blogEntry;
   
   public void loadBlogEntry() throws EntryNotFoundException
   {
      blogEntry = blog.getBlogEntry( blogEntry.getId() );
      if (blogEntry==null) throw new EntryNotFoundException(id);
   }
}

<pages>
   ...

   <page view-id="/entry.xhtml" action="#{entryAction.loadBlogEntry}">
      <param name="blogEntryId" value="#{blogEntry.id}"/>
   </page>
   
   ...
</pages>

It is a matter of taste which implementation you prefer.

The blog demo also demonstrates very simple password authentication, posting to the blog, page fragment caching and atom feed generation.

The Seam distribution includes a command line utility that makes it really easy to set up an Eclipse project, generate some simple Seam skeleton code, and reverse engineer an application from a preexisting database.

This is the easy way to get your feet wet with Seam, and gives you some ammunition for next time you find yourself trapped in an elevator with one of those tedious Ruby guys ranting about how great and wonderful his new toy is for building totally trivial applications that put things in databases.

In this release, seam-gen works best for people with JBoss AS. You can use the generated project with other J2EE or Java EE 5 application servers by making a few manual changes to the project configuration.

You can use seam-gen without Eclipse, but in this tutorial, we want to show you how to use it in conjunction with Eclipse for debugging and integration testing. If you don't want to install Eclipse, you can still follow along with this tutorial—all steps can be performed from the command line.

seam-gen is basically just an intricate Ant script wrapped around Hibernate Tools, together with some templates. That makes it easy to customize if you need to.

Make sure you have JDK 6 (see Section 39.1, “JDK Dependencies” for details), JBoss AS 7.1.1 and Maven 3.x, along with recent versions of Eclipse, the JBoss IDE plugin for Eclipse correctly installed before starting. Add your JBoss installation to the JBoss Server View in Eclipse. Start JBoss in debug mode. Finally, start a command prompt in the directory where you unzipped the Seam distribution.

JBoss has sophisticated support for hot re-deployment of WARs and EARs. Unfortunately, due to bugs in the JVM, repeated redeployment of an EAR—which is common during development—eventually causes the JVM to run out of perm gen space. For this reason, we recommend running JBoss in a JVM with a large perm gen space at development time. If you're running JBoss from JBoss IDE, you can configure this in the server launch configuration, under "VM arguments". We suggest the following values:

-Xms512m -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=512m

If you don't have so much memory available, the following is our minimum recommendation:

-Xms256m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=256m

If you're running JBoss from the command line, you can configure the JVM options in bin/standalone.conf.

If you don't want to bother with this stuff now, you don't have to—come back to it later, when you get your first OutOfMemoryException.

The first thing we need to do is configure seam-gen for your environment: JBoss AS installation directory, project workspace, and database connection. It's easy, just type:

cd jboss-seam-2.3.0
seam setup

And you will be prompted for the needed information:

~/workspace/jboss-seam$ ./seam setup
Buildfile: build.xml

init:

setup:
     [echo] Welcome to seam-gen :-)
    [input] Enter your project workspace (the directory that contains your Seam projects) [C:/Projects] [C:/Projects]
/Users/pmuir/workspace
    [input] Enter your JBoss AS home directory [C:/Program Files/jboss-as-7.1.1.Final] [C:/Program Files/jboss-as-7.1.1.Final]
/Applications/jboss-as-7.1.1.Final
    [input] Enter the project name [myproject] [myproject]
helloworld
     [echo] Accepted project name as: helloworld
    [input] Select a RichFaces skin [blueSky] ([blueSky], emeraldTown, ruby, classic, japanCherry, wine, deepMarine, DEFAULT, plain)

    [input] Is this project deployed as an EAR (with EJB components) or a WAR (with no EJB support) [ear]  ([ear], war, )

    [input] Enter the Java package name for your session beans [com.mydomain.helloworld] [com.mydomain.helloworld]
org.jboss.helloworld
    [input] Enter the Java package name for your entity beans [org.jboss.helloworld] [org.jboss.helloworld]

    [input] Enter the Java package name for your test cases [org.jboss.helloworld.test] [org.jboss.helloworld.test]

    [input] What kind of database are you using? [h2]  ([h2], hsql, mysql, oracle, postgres, mssql, db2, sybase, enterprisedb)
mysql
    [input] Enter the Hibernate dialect for your database [org.hibernate.dialect.MySQLDialect] [org.hibernate.dialect.MySQLDialect]

    [input] Enter the filesystem path to the JDBC driver jar [lib/hsqldb.jar] [lib/hsqldb.jar]
/Users/pmuir/java/mysql.jar
    [input] Enter JDBC driver class for your database [com.mysql.jdbc.Driver] [com.mysql.jdbc.Driver]

    [input] Enter the JDBC URL for your database [jdbc:mysql:///test] [jdbc:mysql:///test]
jdbc:mysql:///helloworld
    [input] Enter database username [sa] [sa]
pmuir
    [input] Enter database password [] []

    [input] skipping input as property hibernate.default_schema.new has already been set.
    [input] Enter the database catalog name (it is OK to leave this blank) [] []

    [input] Are you working with tables that already exist in the database? [n]  (y, [n], )
y
    [input] Do you want to drop and recreate the database tables and data in import.sql each time you deploy? [n]  (y, [n], )
n    

[propertyfile] Creating new property file: /Users/pmuir/workspace/jboss-seam/seam-gen/build.properties
     [echo] Installing JDBC driver jar to JBoss server
     [echo] Type 'seam create-project' to create the new project

BUILD SUCCESSFUL
Total time: 1 minute 32 seconds
~/workspace/jboss-seam $ 

The tool provides sensible defaults, which you can accept by just pressing enter at the prompt.

The most important choice you need to make is between EAR deployment and WAR deployment of your project. EAR projects support EJB 3.0 and require Java EE 5. WAR projects do not support EJB 3.0, but may be deployed to a J2EE environment. The packaging of a WAR is also simpler to understand. If you installed an EJB3-ready application server like JBoss, choose ear. Otherwise, choose war. We'll assume that you've chosen an EAR deployment for the rest of the tutorial, but you can follow exactly the same steps for a WAR deployment.

If you are working with an existing data model, make sure you tell seam-gen that the tables already exist in the database.

The settings are stored in seam-gen/build.properties, but you can also modify them simply by running seam setup a second time.

Now we can create a new project in our Eclipse workspace directory, by typing:

seam new-project
C:\Projects\jboss-seam>seam new-project
Buildfile: build.xml

...

new-project:
     [echo] A new Seam project named 'helloworld' was created in the C:\Projects directory
     [echo] Type 'seam explode' and go to http://localhost:8080/helloworld
     [echo] Eclipse Users: Add the project into Eclipse using File > New > Project and select General > Project (not Java Project)
     [echo] NetBeans Users: Open the project in NetBeans

BUILD SUCCESSFUL
Total time: 7 seconds
C:\Projects\jboss-seam>

This copies the Seam jars, dependent jars and the JDBC driver jar to a new Eclipse project, and generates all needed resources and configuration files, a facelets template file and stylesheet, along with Eclipse metadata and an Ant build script. The Eclipse project will be automatically deployed to an exploded directory structure in JBoss AS as soon as you add the project using New -> Project... -> General -> Project -> Next, typing the Project name (helloworld in this case), and then clicking Finish. Do not select Java Project from the New Project wizard.

If your default JDK in Eclipse is not a Java SE 6 JDK, you will need to select a Java SE 6 compliant JDK using Project -> Properties -> Java Compiler.

Alternatively, you can deploy the project from outside Eclipse by typing seam explode.

Go to http://localhost:8080/helloworld to see a welcome page. This is a facelets page, view/home.xhtml, using the template view/layout/template.xhtml. You can edit this page, or the template, in Eclipse, and see the results immediately, by clicking refresh in your browser.

Don't get scared by the XML configuration documents that were generated into the project directory. They are mostly standard Java EE stuff, the stuff you need to create once and then never look at again, and they are 90% the same between all Seam projects. (They are so easy to write that even seam-gen can do it.)

The generated project includes three database and persistence configurations. The persistence-test.xml and import-test.sql files are used when running the TestNG unit tests against HSQLDB. The database schema and the test data in import-test.sql is always exported to the database before running tests. The myproject-dev-ds.xml, persistence-dev.xmland import-dev.sql files are for use when deploying the application to your development database. The schema might be exported automatically at deployment, depending upon whether you told seam-gen that you are working with an existing database. The myproject-prod-ds.xml, persistence-prod.xmland import-prod.sql files are for use when deploying the application to your production database. The schema is not exported automatically at deployment.

If you're used to traditional action-style web frameworks, you're probably wondering how you can create a simple web page with a stateless action method in Java. If you type:

seam new-action

Seam will prompt for some information, and generate a new facelets page and Seam component for your project.

C:\Projects\jboss-seam>seam new-action
Buildfile: build.xml

validate-workspace:

validate-project:

action-input:
    [input] Enter the Seam component name
ping
    [input] Enter the local interface name [Ping]

    [input] Enter the bean class name [PingBean]

    [input] Enter the action method name [ping]

    [input] Enter the page name [ping]


setup-filters:

new-action:
     [echo] Creating a new stateless session bean component with an action method
     [copy] Copying 1 file to C:\Projects\helloworld\src\hot\org\jboss\helloworld
     [copy] Copying 1 file to C:\Projects\helloworld\src\hot\org\jboss\helloworld
     [copy] Copying 1 file to C:\Projects\helloworld\src\hot\org\jboss\helloworld\test
     [copy] Copying 1 file to C:\Projects\helloworld\src\hot\org\jboss\helloworld\test
     [copy] Copying 1 file to C:\Projects\helloworld\view
     [echo] Type 'seam restart' and go to http://localhost:8080/helloworld/ping.seam

BUILD SUCCESSFUL
Total time: 13 seconds
C:\Projects\jboss-seam>

Because we've added a new Seam component, we need to restart the exploded directory deployment. You can do this by typing seam restart, or by running the restart target in the generated project build.xml file from inside Eclipse. Another way to force a restart is to edit the file resources/META-INF/application.xml in Eclipse. Note that you do not need to restart JBoss each time you change the application.

Now go to http://localhost:8080/helloworld/ping.seam and click the button. You can see the code behind this action by looking in the project src directory. Put a breakpoint in the ping() method, and click the button again.

Finally, locate the PingTest.xml file in the test package and run the integration tests using the TestNG plugin for Eclipse. Alternatively, run the tests using seam test or the test target of the generated build.

When you deploy your Seam application as an exploded directory, you'll get some support for incremental hot deployment at development time. You need to enable debug mode in both Seam and Facelets, by adding this line to components.xml:


<core:init debug="true">

Now, the following files may be redeployed without requiring a full restart of the web application:

But if we want to change any Java code, we still need to do a full restart of the application. (In JBoss this can be handled by configuring deployment scanner mode - more details how to do that are in $JBOSS_HOME/standalone/deployments/README.txt

But if you really want a fast edit/compile/test cycle, Seam supports incremental redeployment of JavaBean components. To make use of this functionality, you must deploy the JavaBean components into the WEB-INF/dev directory, so that they will be loaded by a special Seam classloader, instead of by the WAR or EAR classloader.

You need to be aware of the following limitations:

  • the components must be JavaBean components, they cannot be EJB3 beans (we are working on fixing this limitation)

  • entities can never be hot-deployed

  • components deployed via components.xml may not be hot-deployed

  • the hot-deployable components will not be visible to any classes deployed outside of WEB-INF/dev

  • Seam debug mode must be enabled and jboss-seam-debug.jar must be in WEB-INF/lib

  • You must have the Seam filter installed in web.xml

  • You may see errors if the system is placed under any load and debug is enabled.

If you create a WAR project using seam-gen, incremental hot deployment is available out of the box for classes in the src/hot source directory. However, seam-gen does not support incremental hot deployment for EAR projects.

JBoss Tools is a collection of Eclipse plugins. JBoss Tools a project creation wizard for Seam, Content Assist for the Unified Expression Language (EL) in both facelets and Java code, a graphical editor for Seam configuration files, support for running Seam integration tests from within Eclipse, and much more.

In short, if you are an Eclipse user, then you'll want JBoss Tools!

Please read the latest JBoss Tools documentation at http://docs.jboss.org/tools/latest/en/seam_tools_ref_guide/html/index.html.

JBoss Tools, as with seam-gen, works best with JBoss AS, but it's possible with a few tweaks to get your app running on other application servers. The changes are much like those described for seam-gen later in this reference manual.

Before you get started with Seam 2.3, there are a few things you should be aware of. This process should not be too painful - if you get stuck, just refer back to the updated Seam examples in Seam distribution.

This migration guide assumes you are using Seam 2.2, if you are migrating from Seam 1.2 or 2.0, see the jboss-seam-x.y.z.Final/seam2migration.txt and jboss-seam-x.y.z.Final/seam21migration.txt guide as well.

XML schemas for validation Files that use the Seam 2.2 XSDs should be updated to refer to the 2.3 XSDs, notice the version change. Current namespace pattern is www.jboss.org/schema/seam/* and schemaLocation URL was changed to www.jboss.org/schema/seam/*_-2.3.xsd, where * is Seam module.

Following snippet is an example of component declaration for 2.2 version:

Example 4.1. Before migration of Seam components.xml


<?xml version="1.0" encoding="UTF-8"?>
   <components xmlns="http://jboss.com/products/seam/components"
            xmlns:core="http://jboss.com/products/seam/core"
            xmlns:persistence="http://jboss.com/products/seam/persistence"
            xmlns:security="http://jboss.com/products/seam/security"
            xmlns:theme="http://jboss.com/products/seam/theme"
            xmlns:cache="http://jboss.com/products/seam/cache"
            xmlns:web="http://jboss.com/products/seam/web"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation=
                    "http://jboss.com/products/seam/core http://jboss.com/products/seam/core-2.2.xsd
                 http://jboss.com/products/seam/persistence http://jboss.com/products/seam/persistence-2.2.xsd
                 http://jboss.com/products/seam/security http://jboss.com/products/seam/security-2.2.xsd
                 http://jboss.com/products/seam/theme http://jboss.com/products/seam/theme-2.2.xsd
                 http://jboss.com/products/seam/cache http://jboss.com/products/seam/cache-2.2.xsd
                 http://jboss.com/products/seam/web http://jboss.com/products/seam/web-2.2.xsd
                 http://jboss.com/products/seam/components http://jboss.com/products/seam/components-2.2.xsd">

And finally migrated declaration of components.xml for 2.3 version:

Example 4.2. Migrated components.xml


<?xml version="1.0" encoding="UTF-8"?>
      <components xmlns="http://jboss.org/schema/seam/components"
                  xmlns:core="http://jboss.org/schema/seam/core"
                  xmlns:persistence="http://jboss.org/schema/seam/persistence"
                  xmlns:security="http://jboss.org/schema/seam/security"
                  xmlns:theme="http://jboss.org/schema/seam/theme"
                  xmlns:cache="http://jboss.org/schema/seam/cache"
                  xmlns:web="http://jboss.org/schema/seam/web"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation=
                          "http://jboss.org/schema/seam/core http://jboss.org/schema/seam/core-2.3.xsd
                       http://jboss.org/schema/seam/persistence http://jboss.org/schema/seam/persistence-2.3.xsd
                       http://jboss.org/schema/seam/security http://jboss.org/schema/seam/security-2.3.xsd
                       http://jboss.org/schema/seam/theme http://jboss.org/schema/seam/theme-2.3.xsd
                       http://jboss.org/schema/seam/cache http://jboss.org/schema/seam/cache-2.3.xsd
                       http://jboss.org/schema/seam/web http://jboss.org/schema/seam/web-2.3.xsd
                       http://jboss.org/schema/seam/components http://jboss.org/schema/seam/components-2.3.xsd">

Next remainning migration step is pages.xml file(s) as well as other files only requires that the schemas be upgraded.



Seam 2.3 technology upgrade includes also Java EE 6 upgrade so you need to update the following descriptors

Examples of changed headers with correct versions are the following:





Seam 2.3 can integrate with the major upgrades in Java EE (from 5 to 6). You can use persistence with JPA 2, EJB 3.1 and Bean Validation. Almost all EE 6 technology upgrade requires to change XML schema declaration. See Section 4.1.2, “Java EE 6 schema changes”

Configuration file faces-config.xml is not required to be in your application, so for simple using of JSF 2 you need to migrate only web.xml. If you anyway would like to have it, change the XML schema declaration as is described in Example 4.8, “faces-config.xml”.

All your application JSF templates should use only facelets technology as JSP is deprecated.

In facelet templates there are required to convert <head>/<body> tags to ><h:head>/<h:body>respectively.

Depending on what JSF components that you use like Richfaces or Icefaces, there has to be some differences when upgrading from JSF 1.x to JSF 2.x. You may need to upgrade libraries entirely. Consult any component framework documentation on those changes. This migration doesn't cover these migration steps.

Using JPA 2 requires to change version to 2.0 in persistence.xml, see Example 4.5, “persistence.xml” file and version in application.xml should be 6 if you are using EAR - see Example 4.6, “application.xml” or version in web.xml file change to 3.0 if you use only WAR - look at Example 4.7, “web.xml”.

What is important for developers, most application can use just WAR with EJB 3.1 and doesn't have to package application as EAR.

JPA 2.0 is backward compatible with JPA 1.0, so you don't have to migrate any JPA annotation or classes. JPA 2.0 is more like enhancement to JPA 1.0.

Next level is migration of your target runtime. Seam 2.3 uses JBoss AS 7 as default target runtime.

If you are using for development or testing default datasource in JBoss AS 7.1, you need to change datasource JNDI in your persistence.xml from java:/DefaultDS to java:jboss/datasources/ExampleDS.

JBoss AS 7 has got refactored classloading model. Classloading of bundled or provided libraries can be managed in jboss-deployment-structure.xml or in META-INF/MANIFEST.MF file in section Dependencies. This migration documentation prefers using of jboss-deployment-structure.xml file, which should be placed in META-INF directory of your WAR or EAR application according to your application type.

For full EAR projects, the jboss-deployment-structure.xml will be located in the _your_ear_/META-INF directory.

For Web (non-ear) projects, the jboss-deployment-structure.xml will be located in the _your_war_/WEB-INF directory.

Minimal content for Seam 2.3 based application is:


<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.0">
     <deployment>
         <dependencies>
            <module name="org.dom4j" export="true"/>
            <module name="org.apache.commons.collections" export="true"/>
             <module name="javax.faces.api" export="true"/> <!-- keep there only if you use JSF as view technology -->
           </dependencies>
     </deployment>  
   </jboss-deployment-structure>

More details are described in JBoss AS 7 documentation.

You can also include now any database descriptor (*-ds.xml) files into your project in the META-INF directory, and the data source will be deployed automatically when deployed to a JBoss AS 7.1 Application Server. The structure of the file though has changed. Before the datasource file was a simple xml based file, but now is an IronJacamar based file. Iron-Jacamar is the JBoss' JCA (Java Connector Architecture) project. Below on Example 4.9, “Sample Seam 2.2 Datasource Descriptor File” is the former datasource for JBoss AS 4/5, and Example 4.10, “Ironjacamar Datasource Descriptor File” shows the conversion to IronJacamar using the same driver, url, and credentials.



SeamTest and JBoss Embedded are legacy components and have many limitations and we doesn't support it like we did in Seam 2.2.

We now bring Arquillian as the replacement of JBoss Embedded and you should extend org.jboss.seam.mock.JUnitSeamTest instead of org.jboss.seam.mock.SeamTest, DBUnit testing is provided by org.jboss.seam.mock.DBJUnitSeamTest instead of org.jboss.seam.mock.DBUnitSeamTest. Due assertion issues with TestNG framework and Arquillian, we use JUnit as preferred test framework. Migration to Junit and Arquillian goes in the following steps:

  1. Add
    @RunWith(Arquillian.class)
    annotation to your test class.
  2. Your test class should extend org.jboss.seam.mock.JUnitSeamTest instead of org.jboss.seam.mock.SeamTest.
  3. Add a method like
    @Deployment(name="_your_test_name_")
    
    @OverProtocol("Servlet 3.0")
    public static org.jboss.shrinkwrap.api.Archive<?> createDeployment(){}
    for creating test deployment archive. The following example is taken from Registration example testsuite. It imports the .ear archive buit with "mvn package", adds the test class to the deployment and replaces the WEB-INF/web.xml file with a SeamTest-specific version.
    @Deployment(name="RegisterTest")
    
    @OverProtocol("Servlet 3.0")
    public static Archive<?> createDeployment()
    {
       EnterpriseArchive er = ShrinkWrap.create(ZipImporter.class, "seam-registration.ear").importFrom(new File("../registration-ear/target/seam-registration.ear"))
                  .as(EnterpriseArchive.class);
       WebArchive web = er.getAsType(WebArchive.class, "registration-web.war");
       web.addClasses(RegisterTest.class);
       // Install org.jboss.seam.mock.MockSeamListener
       web.delete("/WEB-INF/web.xml");
       web.addAsWebInfResource("web.xml");
       return er;
    }
  4. Create a SeamTest-specific web.xml contaning the org.jboss.seam.mock.MockSeamListener, instead of the usual org.jboss.seam.servlet.SeamListener.
    
    
    <?xml version="1.0" ?>
    <web-app version="3.0"
             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_3_0.xsd">
             
        <listener>
            <listener-class>org.jboss.seam.mock.MockSeamListener</listener-class>
        </listener>

    </web-app>
  5. Add arquillian.xml file into root of your classpath for running Arquillian test(s). The file content should specify path to remote or managed container and some specific options for JVM or Arquillian. The example of arquillian file is at jboss-seam-x.y.z.Final/examples/booking/booking-tests/src/test/resources-integration/arquillian.xml:
    
    <?xml version="1.0" encoding="UTF-8"?>
    <arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://jboss.org/schema/arquillian"
        xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
        <engine>
            <property name="deploymentExportPath">target/</property>
        </engine>
        <container qualifier="jboss" default="true">
            <configuration>
                <property name="javaVmArguments">-Xmx1024m -XX:MaxPermSize=512m</property>
                <property name="jbossHome">target/jboss-as-${version.jbossas7}</property>
            </configuration>
        </container>
    </arquillian>

More details in Seam reference documentation guide in Section 38.2, “Integration testing Seam components”.

The "provided" platform is now JBoss AS 7.1.x as is written above, therefore all Java EE dependencies included in AS 7 are now marked as provided.

The two core concepts in Seam are the notion of a context and the notion of a component. Components are stateful objects, usually EJBs, and an instance of a component is associated with a context, and given a name in that context. Bijection provides a mechanism for aliasing internal component names (instance variables) to contextual names, allowing component trees to be dynamically assembled, and reassembled by Seam.

Let's start by describing the contexts built in to Seam.

Seam contexts are created and destroyed by the framework. The application does not control context demarcation via explicit Java API calls. Context are usually implicit. In some cases, however, contexts are demarcated via annotations.

The basic Seam contexts are:

You will recognize some of these contexts from servlet and related specifications. However, two of them might be new to you: conversation context, and business process context. One reason state management in web applications is so fragile and error-prone is that the three built-in contexts (request, session and application) are not especially meaningful from the point of view of the business logic. A user login session, for example, is a fairly arbitrary construct in terms of the actual application work flow. Therefore, most Seam components are scoped to the conversation or business process contexts, since they are the contexts which are most meaningful in terms of the application.

Let's look at each context in turn.

The conversation context is a truly central concept in Seam. A conversation is a unit of work from the point of view of the user. It might span several interactions with the user, several requests, and several database transactions. But to the user, a conversation solves a single problem. For example, "book hotel", "approve contract", "create order" are all conversations. You might like to think of a conversation implementing a single "use case" or "user story", but the relationship is not necessarily quite exact.

A conversation holds state associated with "what the user is doing now, in this window". A single user may have multiple conversations in progress at any point in time, usually in multiple windows. The conversation context allows us to ensure that state from the different conversations does not collide and cause bugs.

It might take you some time to get used to thinking of applications in terms of conversations. But once you get used to it, we think you'll love the notion, and never be able to not think in terms of conversations again!

Some conversations last for just a single request. Conversations that span multiple requests must be demarcated using annotations provided by Seam.

Some conversations are also tasks. A task is a conversation that is significant in terms of a long-running business process, and has the potential to trigger a business process state transition when it is successfully completed. Seam provides a special set of annotations for task demarcation.

Conversations may be nested, with one conversation taking place "inside" a wider conversation. This is an advanced feature.

Usually, conversation state is actually held by Seam in the servlet session between requests. Seam implements configurable conversation timeout, automatically destroying inactive conversations, and thus ensuring that the state held by a single user login session does not grow without bound if the user abandons conversations.

Seam serializes processing of concurrent requests that take place in the same long-running conversation context, in the same process.

Alternatively, Seam may be configured to keep conversational state in the client browser.

Neither the servlet nor EJB specifications define any facilities for managing concurrent requests originating from the same client. The servlet container simply lets all threads run concurrently and leaves enforcing thread safeness to application code. The EJB container allows stateless components to be accessed concurrently, and throws an exception if multiple threads access a stateful session bean.

This behavior might have been okay in old-style web applications which were based around fine-grained, synchronous requests. But for modern applications which make heavy use of many fine-grained, asynchronous (AJAX) requests, concurrency is a fact of life, and must be supported by the programming model. Seam weaves a concurrency management layer into its context model.

The Seam session and application contexts are multithreaded. Seam will allow concurrent requests in a context to be processed concurrently. The event and page contexts are by nature single threaded. The business process context is strictly speaking multi-threaded, but in practice concurrency is sufficiently rare that this fact may be disregarded most of the time. Finally, Seam enforces a single thread per conversation per process model for the conversation context by serializing concurrent requests in the same long-running conversation context.

Since the session context is multithreaded, and often contains volatile state, session scope components are always protected by Seam from concurrent access so long as the Seam interceptors are not disabled for that component. If interceptors are disabled, then any thread-safety that is required must be implemented by the component itself. Seam serializes requests to session scope JavaBeans by default (and detects and breaks any deadlocks that occur). This is not the default behaviour for application scoped components however, since application scoped components do not usually hold volatile state and because synchronization at the global level is extremely expensive. However, you can force a serialized threading model on any JavaBean component by adding the @Synchronized annotation.

This concurrency model means that AJAX clients can safely use volatile session and conversational state, without the need for any special work on the part of the developer.

Seam components are POJOs (Plain Old Java Objects). In particular, they are JavaBeans or EJB 3.0 enterprise beans. While Seam does not require that components be EJBs and can even be used without an EJB 3.0 compliant container, Seam was designed with EJB 3.0 in mind and includes deep integration with EJB 3.0. Seam supports the following component types.

All seam components need a name. We can assign a name to a component using the @Name annotation:

@Name("loginAction")

@Stateless
public class LoginAction implements Login { 
    ... 
}

This name is the seam component name and is not related to any other name defined by the EJB specification. However, seam component names work just like JSF managed bean names and you can think of the two concepts as identical.

@Name is not the only way to define a component name, but we always need to specify the name somewhere. If we don't, then none of the other Seam annotations will function.

Whenever Seam instantiates a component, it binds the new instance to a variable in the scope configured for the component that matches the component name. This behavior is identical to how JSF managed beans work, except that Seam allows you to configure this mapping using annotations rather than XML. You can also programmatically bind a component to a context variable. This is useful if a particular component serves more than one role in the system. For example, the currently logged in User might be bound to the currentUser session context variable, while a User that is the subject of some administration functionality might be bound to the user conversation context variable. Be careful, though, because through a programmatic assignment, it's possible to overwrite a context variable that has a reference to a Seam component, potentially confusing matters.

For very large applications, and for built-in seam components, qualified component names are often used to avoid naming conflicts.

@Name("com.jboss.myapp.loginAction")

@Stateless
public class LoginAction implements Login { 
    ... 
}

We may use the qualified component name both in Java code and in JSF's expression language:


<h:commandButton type="submit" value="Login"
                 action="#{com.jboss.myapp.loginAction.login}"/>

Since this is noisy, Seam also provides a means of aliasing a qualified name to a simple name. Add a line like this to the components.xml file:


<factory name="loginAction" scope="STATELESS" value="#{com.jboss.myapp.loginAction}"/>

All of the built-in Seam components have qualified names but can be accessed through their unqualified names due to the namespace import feature of Seam. The components.xml file included in the Seam JAR defines the following namespaces.


<components xmlns="http://jboss.org/schema/seam/components">
    
    <import>org.jboss.seam.core</import>
    <import>org.jboss.seam.cache</import>
    <import>org.jboss.seam.transaction</import>
    <import>org.jboss.seam.framework</import>
    <import>org.jboss.seam.web</import>
    <import>org.jboss.seam.faces</import>
    <import>org.jboss.seam.international</import>
    <import>org.jboss.seam.theme</import>
    <import>org.jboss.seam.pageflow</import>
    <import>org.jboss.seam.bpm</import>
    <import>org.jboss.seam.jms</import>
    <import>org.jboss.seam.mail</import>
    <import>org.jboss.seam.security</import>
    <import>org.jboss.seam.security.management</import>  
    <import>org.jboss.seam.security.permission</import>
    <import>org.jboss.seam.captcha</import>
    <import>org.jboss.seam.excel.exporter</import>
    <!-- ... --->
</components>

When attempting to resolve an unqualified name, Seam will check each of those namespaces, in order. You can include additional namespaces in your application's components.xml file for application-specific namespaces.

Dependency injection or inversion of control is by now a familiar concept to most Java developers. Dependency injection allows a component to obtain a reference to another component by having the container "inject" the other component to a setter method or instance variable. In all dependency injection implementations that we have seen, injection occurs when the component is constructed, and the reference does not subsequently change for the lifetime of the component instance. For stateless components, this is reasonable. From the point of view of a client, all instances of a particular stateless component are interchangeable. On the other hand, Seam emphasizes the use of stateful components. So traditional dependency injection is no longer a very useful construct. Seam introduces the notion of bijection as a generalization of injection. In contrast to injection, bijection is:

In essence, bijection lets you alias a context variable to a component instance variable, by specifying that the value of the instance variable is injected, outjected, or both. Of course, we use annotations to enable bijection.

The @In annotation specifies that a value should be injected, either into an instance variable:

@Name("loginAction")

@Stateless
public class LoginAction implements Login { 
    @In User user;
    ... 
}

or into a setter method:

@Name("loginAction")

@Stateless
public class LoginAction implements Login { 
    User user;
    
    @In
    public void setUser(User user) {
        this.user=user;
    }
    
    ... 
}

By default, Seam will do a priority search of all contexts, using the name of the property or instance variable that is being injected. You may wish to specify the context variable name explicitly, using, for example, @In("currentUser").

If you want Seam to create an instance of the component when there is no existing component instance bound to the named context variable, you should specify @In(create=true). If the value is optional (it can be null), specify @In(required=false).

For some components, it can be repetitive to have to specify @In(create=true) everywhere they are used. In such cases, you can annotate the component @AutoCreate, and then it will always be created, whenever needed, even without the explicit use of create=true.

You can even inject the value of an expression:

@Name("loginAction")

@Stateless
public class LoginAction implements Login { 
    @In("#{user.username}") String username;
    ... 
}

Injected values are disinjected (i.e., set to null) immediately after method completion and outjection.

(There is much more information about component lifecycle and injection in the next chapter.)

The @Out annotation specifies that an attribute should be outjected, either from an instance variable:

@Name("loginAction")

@Stateless
public class LoginAction implements Login { 
    @Out User user;
    ... 
}

or from a getter method:

@Name("loginAction")

@Stateless
public class LoginAction implements Login { 
    User user;
    
    @Out
    public User getUser() {
        return user;
    }
    
    ... 
}

An attribute may be both injected and outjected:

@Name("loginAction")

@Stateless
public class LoginAction implements Login { 
    @In @Out User user;
    ... 
}

or:

@Name("loginAction")

@Stateless
public class LoginAction implements Login { 
    User user;
    
    @In
    public void setUser(User user) {
        this.user=user;
    }
    
    @Out
    public User getUser() {
        return user;
    }
    
    ... 
}

The @Install annotation lets you control conditional installation of components that are required in some deployment scenarios and not in others. This is useful if:

@Install works by letting you specify precedence and dependencies.

The precedence of a component is a number that Seam uses to decide which component to install when there are multiple classes with the same component name in the classpath. Seam will choose the component with the higher precedence. There are some predefined precedence values (in ascending order):

Suppose we have a component named messageSender that talks to a JMS queue.

@Name("messageSender") 

public class MessageSender {
    public void sendMessage() {
        //do something with JMS
    }
}

In our unit tests, we don't have a JMS queue available, so we would like to stub out this method. We'll create a mock component that exists in the classpath when unit tests are running, but is never deployed with the application:

@Name("messageSender") 

@Install(precedence=MOCK)
public class MockMessageSender extends MessageSender {
    public void sendMessage() {
        //do nothing!
    }
}

The precedence helps Seam decide which version to use when it finds both components in the classpath.

This is nice if we are able to control exactly which classes are in the classpath. But if I'm writing a reusable framework with many dependencies, I don't want to have to break that framework across many jars. I want to be able to decide which components to install depending upon what other components are installed, and upon what classes are available in the classpath. The @Install annotation also controls this functionality. Seam uses this mechanism internally to enable conditional installation of many of the built-in components. However, you probably won't need to use it in your application.

Who is not totally fed up with seeing noisy code like this?

private static final Log log = LogFactory.getLog(CreateOrderAction.class);

        
public Order createOrder(User user, Product product, int quantity) {
    if ( log.isDebugEnabled() ) {
        log.debug("Creating new order for user: " + user.username() + 
            " product: " + product.name() 
            + " quantity: " + quantity);
    }
    return new Order(user, product, quantity);
}

It is difficult to imagine how the code for a simple log message could possibly be more verbose. There is more lines of code tied up in logging than in the actual business logic! I remain totally astonished that the Java community has not come up with anything better in 10 years.

Seam provides a logging API that simplifies this code significantly:

@Logger private Log log;

        
public Order createOrder(User user, Product product, int quantity) {
    log.debug("Creating new order for user: #0 product: #1 quantity: #2", user.username(), product.name(), quantity);
    return new Order(user, product, quantity);
}

It doesn't matter if you declare the log variable static or not — it will work either way, except for entity bean components which require the log variable to be static.

Note that we don't need the noisy if ( log.isDebugEnabled() ) guard, since string concatenation happens inside the debug() method. Note also that we don't usually need to specify the log category explicitly, since Seam knows what component it is injecting the Log into.

If User and Product are Seam components available in the current contexts, it gets even better:

@Logger private Log log;

        
public Order createOrder(User user, Product product, int quantity) {
    log.debug("Creating new order for user: #{user.username} product: #{product.name} quantity: #0", quantity);
    return new Order(user, product, quantity);
}

Seam logging automagically chooses whether to send output to log4j or JDK logging. If log4j is in the classpath, Seam with use it. If it is not, Seam will use JDK logging.

Many application servers feature an amazingly broken implementation of HttpSession clustering, where changes to the state of mutable objects bound to the session are only replicated when the application calls setAttribute() explicitly. This is a source of bugs that can not effectively be tested for at development time, since they will only manifest when failover occurs. Furthermore, the actual replication message contains the entire serialized object graph bound to the session attribute, which is inefficient.

Of course, EJB stateful session beans must perform automatic dirty checking and replication of mutable state and a sophisticated EJB container can introduce optimizations such as attribute-level replication. Unfortunately, not all Seam users have the good fortune to be working in an environment that supports EJB 3.0. So, for session and conversation scoped JavaBean and entity bean components, Seam provides an extra layer of cluster-safe state management over the top of the web container session clustering.

For session or conversation scoped JavaBean components, Seam automatically forces replication to occur by calling setAttribute() once in every request that the component was invoked by the application. Of course, this strategy is inefficient for read-mostly components. You can control this behavior by implementing the org.jboss.seam.core.Mutable interface, or by extending org.jboss.seam.core.AbstractMutable, and writing your own dirty-checking logic inside the component. For example,

@Name("account")

public class Account extends AbstractMutable
{
    private BigDecimal balance;
    
    public void setBalance(BigDecimal balance)
    {
        setDirty(this.balance, balance);
        this.balance = balance;
    }
    
    public BigDecimal getBalance()
    {
        return balance;
    }
    
    ...
    
}

Or, you can use the @ReadOnly annotation to achieve a similar effect:

@Name("account")

public class Account
{
    private BigDecimal balance;
    
    public void setBalance(BigDecimal balance)
    {
        this.balance = balance;
    }
    
    @ReadOnly
    public BigDecimal getBalance()
    {
        return balance;
    }
    
    ...
    
}

For session or conversation scoped entity bean components, Seam automatically forces replication to occur by calling setAttribute() once in every request, unless the (conversation-scoped) entity is currently associated with a Seam-managed persistence context, in which case no replication is needed. This strategy is not necessarily efficient, so session or conversation scope entity beans should be used with care. You can always write a stateful session bean or JavaBean component to "manage" the entity bean instance. For example,

@Stateful

@Name("account")
public class AccountManager extends AbstractMutable
{
    private Account account; // an entity bean
    
    @Unwrap
    public Account getAccount()
    {
        return account;
    }
    
    ...
    
}

Note that the EntityHome class in the Seam Application Framework provides a great example of managing an entity bean instance using a Seam component.

We often need to work with objects that are not Seam components. But we still want to be able to inject them into our components using @In and use them in value and method binding expressions, etc. Sometimes, we even need to tie them into the Seam context lifecycle (@Destroy, for example). So the Seam contexts can contain objects which are not Seam components, and Seam provides a couple of nice features that make it easier to work with non-component objects bound to contexts.

The factory component pattern lets a Seam component act as the instantiator for a non-component object. A factory method will be called when a context variable is referenced but has no value bound to it. We define factory methods using the @Factory annotation. The factory method binds a value to the context variable, and determines the scope of the bound value. There are two styles of factory method. The first style returns a value, which is bound to the context by Seam:

@Factory(scope=CONVERSATION)

public List<Customer> getCustomerList() { 
    return ... ;
} 

The second style is a method of type void which binds the value to the context variable itself:

@DataModel List<Customer> customerList;


@Factory("customerList")
public void initCustomerList() { 
    customerList = ...  ;
} 

In both cases, the factory method is called when we reference the customerList context variable and its value is null, and then has no further part to play in the lifecycle of the value. An even more powerful pattern is the manager component pattern. In this case, we have a Seam component that is bound to a context variable, that manages the value of the context variable, while remaining invisible to clients.

A manager component is any component with an @Unwrap method. This method returns the value that will be visible to clients, and is called every time a context variable is referenced.

@Name("customerList")

@Scope(CONVERSATION)
public class CustomerListManager
{
    ...
    
    @Unwrap
    public List<Customer> getCustomerList() { 
        return ... ;
    }
}

The manager component pattern is especially useful if we have an object where you need more control over the lifecycle of the component. For example, if you have a heavyweight object that needs a cleanup operation when the context ends you could @Unwrap the object, and perform cleanup in the @Destroy method of the manager component.

@Name("hens")

@Scope(APPLICATION) 
public class HenHouse
{
    Set<Hen> hens;
    
    @In(required=false) Hen hen;
    
    @Unwrap
    public List<Hen> getHens()
    {
        if (hens == null)
        {
            // Setup our hens
        }
        return hens;
    }
    
    @Observer({"chickBorn", "chickenBoughtAtMarket"})
    public addHen()
    {
        hens.add(hen);
    }
    
    @Observer("chickenSoldAtMarket")
    public removeHen()
    {
        hens.remove(hen);
    }
    
    @Observer("foxGetsIn")
    public removeAllHens()
    {
        hens.clear();
    }
    ...
} 

Here the managed component observes many events which change the underlying object. The component manages these actions itself, and because the object is unwrapped on every access, a consistent view is provided.

The philosophy of minimizing XML-based configuration is extremely strong in Seam. Nevertheless, there are various reasons why we might want to configure a Seam component using XML: to isolate deployment-specific information from the Java code, to enable the creation of re-usable frameworks, to configure Seam's built-in functionality, etc. Seam provides two basic approaches to configuring components: configuration via property settings in a properties file or in web.xml, and configuration via components.xml.

The components.xml file is a bit more powerful than property settings. It lets you:

A components.xml file may appear in one of three different places:

Usually, Seam components are installed when the deployment scanner discovers a class with a @Name annotation sitting in an archive with a seam.properties file or a META-INF/components.xml file. (Unless the component has an @Install annotation indicating it should not be installed by default.) The components.xml file lets us handle special cases where we need to override the annotations.

For example, the following components.xml file installs jBPM:


<components xmlns="http://jboss.org/schema/seam/components" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:bpm="http://jboss.org/schema/seam/bpm">
    <bpm:jbpm/>
</components>

This example does the same thing:


<components>
    <component class="org.jboss.seam.bpm.Jbpm"/>
</components>

This one installs and configures two different Seam-managed persistence contexts:


<components xmlns="http://jboss.org/schema/seam/components" 
            xmlns:persistence="http://jboss.org/schema/seam/persistence"

    <persistence:managed-persistence-context name="customerDatabase"
                       persistence-unit-jndi-name="java:/customerEntityManagerFactory"/>
        
    <persistence:managed-persistence-context name="accountingDatabase"
                       persistence-unit-jndi-name="java:/accountingEntityManagerFactory"/>            

</components>

As does this one:


<components>
    <component name="customerDatabase" 
              class="org.jboss.seam.persistence.ManagedPersistenceContext">
        <property name="persistenceUnitJndiName">java:/customerEntityManagerFactory</property>
    </component>
    
    <component name="accountingDatabase"
              class="org.jboss.seam.persistence.ManagedPersistenceContext">
        <property name="persistenceUnitJndiName">java:/accountingEntityManagerFactory</property>
    </component>
</components>

This example creates a session-scoped Seam-managed persistence context (this is not recommended in practice):


<components xmlns="http://jboss.org/schema/seam/components" 
            xmlns:persistence="http://jboss.org/schema/seam/persistence"

  <persistence:managed-persistence-context name="productDatabase" 
                                          scope="session"
                     persistence-unit-jndi-name="java:/productEntityManagerFactory"/>        

</components>

<components>
            
    <component name="productDatabase"
              scope="session"
              class="org.jboss.seam.persistence.ManagedPersistenceContext">
        <property name="persistenceUnitJndiName">java:/productEntityManagerFactory</property>
    </component>

</components>

It is common to use the auto-create option for infrastructural objects like persistence contexts, which saves you from having to explicitly specify create=true when you use the @In annotation.


<components xmlns="http://jboss.org/schema/seam/components" 
            xmlns:persistence="http://jboss.org/schema/seam/persistence"

  <persistence:managed-persistence-context name="productDatabase" 
                                    auto-create="true"
                     persistence-unit-jndi-name="java:/productEntityManagerFactory"/>        

</components>

<components>
            
    <component name="productDatabase"
        auto-create="true"
              class="org.jboss.seam.persistence.ManagedPersistenceContext">
        <property name="persistenceUnitJndiName">java:/productEntityManagerFactory</property>
    </component>

</components>

The <factory> declaration lets you specify a value or method binding expression that will be evaluated to initialize the value of a context variable when it is first referenced.


<components>

    <factory name="contact" method="#{contactManager.loadContact}" scope="CONVERSATION"/>

</components>

You can create an "alias" (a second name) for a Seam component like so:


<components>

    <factory name="user" value="#{actor}" scope="STATELESS"/>

</components>

You can even create an "alias" for a commonly used expression:


<components>

    <factory name="contact" value="#{contactManager.contact}" scope="STATELESS"/>

</components>

It is especially common to see the use of auto-create="true" with the <factory> declaration:


<components>

    <factory name="session" value="#{entityManager.delegate}" scope="STATELESS" auto-create="true"/>

</components>

Sometimes we want to reuse the same components.xml file with minor changes during both deployment and testing. Seam lets you place wildcards of the form @wildcard@ in the components.xml file which can be replaced either by your Ant build script (at deployment time) or by providing a file named components.properties in the classpath (at development time). You'll see this approach used in the Seam examples.

Properties of string, primitive or primitive wrapper type may be configured just as you would expect:

org.jboss.seam.core.manager.conversationTimeout 60000

<core:manager conversation-timeout="60000"/>

<component name="org.jboss.seam.core.manager">
    <property name="conversationTimeout">60000</property>
</component>

Arrays, sets and lists of strings or primitives are also supported:

org.jboss.seam.bpm.jbpm.processDefinitions order.jpdl.xml, return.jpdl.xml, inventory.jpdl.xml

<bpm:jbpm>
    <bpm:process-definitions>
        <value>order.jpdl.xml</value>
        <value>return.jpdl.xml</value>
        <value>inventory.jpdl.xml</value>
    </bpm:process-definitions>
</bpm:jbpm>

<component name="org.jboss.seam.bpm.jbpm">
    <property name="processDefinitions">
        <value>order.jpdl.xml</value>
        <value>return.jpdl.xml</value>
        <value>inventory.jpdl.xml</value>
    </property>
</component>

Even maps with String-valued keys and string or primitive values are supported:


<component name="issueEditor">
    <property name="issueStatuses">
        <key>open</key> <value>open issue</value>
        <key>resolved</key> <value>issue resolved by developer</value>
        <key>closed</key> <value>resolution accepted by user</value>
    </property>
</component>

When configuring multi-valued properties, by default, Seam will preserve the order in which you place the attributes in components.xml (unless you use a SortedSet/SortedMap then Seam will use TreeMap/TreeSet). If the property has a concrete type (for example LinkedList) Seam will use that type.

You can also override the type by specifying a fully qualified class name:


<component name="issueEditor">
   <property name="issueStatusOptions" type="java.util.LinkedHashMap">
      <key>open</key> <value>open issue</value>
      <key>resolved</key> <value>issue resolved by developer</value>
      <key>closed</key> <value>resolution accepted by user</value>
   </property>
</component>

Finally, you may wire together components using a value-binding expression. Note that this is quite different to injection using @In, since it happens at component instantiation time instead of invocation time. It is therefore much more similar to the dependency injection facilities offered by traditional IoC containers like JSF or Spring.


<drools:managed-working-memory name="policyPricingWorkingMemory"
    rule-base="#{policyPricingRules}"/>

<component name="policyPricingWorkingMemory"
    class="org.jboss.seam.drools.ManagedWorkingMemory">
    <property name="ruleBase">#{policyPricingRules}</property>
</component>

Seam also resolves an EL expression string prior to assigning the initial value to the bean property of the component. So you can inject some contextual data into your components.


<component name="greeter" class="com.example.action.Greeter">
    <property name="message">Nice to see you, #{identity.username}!</property>
</component>

However, there is one important exception. If the type of the property to which the initial value is being assigned is either a Seam ValueExpression or MethodExpression, then the evaluation of the EL is deferred. Instead, the appropriate expression wrapper is created and assigned to the property. The message templates on the Home component from the Seam Application Framework serve as an example.


<framework:entity-home name="myEntityHome"
    class="com.example.action.MyEntityHome" entity-class="com.example.model.MyEntity"
    created-message="'#{myEntityHome.instance.name}' has been successfully added."/>

Inside the component, you can access the expression string by calling getExpressionString() on the ValueExpression or MethodExpression. If the property is a ValueExpression, you can resolve the value using getValue() and if the property is a MethodExpression, you can invoke the method using invoke(Object args...). Obviously, to assign a value to a MethodExpression property, the entire initial value must be a single EL expression.

Throughout the examples, there have been two competing ways of declaring components: with and without the use of XML namespaces. The following shows a typical components.xml file without namespaces:


<?xml version="1.0" encoding="UTF-8"?>
<components xmlns="http://jboss.org/schema/seam/components"
            xsi:schemaLocation="http://jboss.org/schema/seam/components http://jboss.org/schema/seam/components-2.3.xsd">

    <component class="org.jboss.seam.core.init">
        <property name="debug">true</property>
        <property name="jndiPattern">@jndiPattern@</property>
    </component>
    
</components>

As you can see, this is somewhat verbose. Even worse, the component and attribute names cannot be validated at development time.

The version with using namespaces looks like this:


<?xml version="1.0" encoding="UTF-8"?>
<components xmlns="http://jboss.org/schema/seam/components"
            xmlns:core="http://jboss.org/schema/seam/core"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation=
                "http://jboss.org/schema/seam/core http://jboss.org/schema/seam/core-2.3.xsd 
                 http://jboss.org/schema/seam/components http://jboss.org/schema/seam/components-2.3.xsd">

    <core:init debug="true" jndi-pattern="@jndiPattern@"/>

</components>

Even though the schema declarations are verbose, the actual XML content is lean and easy to understand. The schemas provide detailed information about each component and the attributes available, allowing XML editors to offer intelligent autocomplete. The use of namespaced elements makes generating and maintaining correct components.xml files much simpler.

Now, this works great for the built-in Seam components, but what about user components? There are two options. First, Seam supports mixing the two models, allowing the use of the generic <component> declarations for user components, along with namespaced declarations for built-in components. But even better, Seam allows you to quickly declare namespaces for your own components.

Any Java package can be associated with an XML namespace by annotating the package with the @Namespace annotation. (Package-level annotations are declared in a file named package-info.java in the package directory.) Here is an example from the seampay demo:

@Namespace(value="http://jboss.org/schema/seam/examples/seampay")

package org.jboss.seam.example.seampay;
import org.jboss.seam.annotations.Namespace;

That is all you need to do to use the namespaced style in components.xml! Now we can write:


<components xmlns="http://jboss.org/schema/seam/components"
            xmlns:pay="http://jboss.org/schema/seam/examples/seampay"
            ... >

    <pay:payment-home new-instance="#{newPayment}"
                      created-message="Created a new payment to #{newPayment.payee}" />

    <pay:payment name="newPayment"
                 payee="Somebody"
                 account="#{selectedAccount}"
                 payment-date="#{currentDatetime}"
                 created-date="#{currentDatetime}" />
     ...
</components>

Or:


<components xmlns="http://jboss.org/schema/seam/components"
            xmlns:pay="http://jboss.org/schema/seam/examples/seampay"
            ... >

    <pay:payment-home>
        <pay:new-instance>"#{newPayment}"</pay:new-instance>
        <pay:created-message>Created a new payment to #{newPayment.payee}</pay:created-message>
    </pay:payment-home>
    
    <pay:payment name="newPayment">
        <pay:payee>Somebody"</pay:payee>
        <pay:account>#{selectedAccount}</pay:account>
        <pay:payment-date>#{currentDatetime}</pay:payment-date>
        <pay:created-date>#{currentDatetime}</pay:created-date>
     </pay:payment>
     ...
</components>

These examples illustrate the two usage models of a namespaced element. In the first declaration, the <pay:payment-home> references the paymentHome component:

package org.jboss.seam.example.seampay;

...
@Name("paymentHome")
public class PaymentController
    extends EntityHome<Payment>
{
    ... 
}

The element name is the hyphenated form of the component name. The attributes of the element are the hyphenated form of the property names.

In the second declaration, the <pay:payment> element refers to the Payment class in the org.jboss.seam.example.seampay package. In this case Payment is an entity that is being declared as a Seam component:

package org.jboss.seam.example.seampay;

...
@Entity
public class Payment
    implements Serializable
{
    ...
}

If we want validation and autocompletion to work for user-defined components, we will need a schema. Seam does not yet provide a mechanism to automatically generate a schema for a set of components, so it is necessary to generate one manually. The schema definitions for the standard Seam packages can be used for guidance.

The following are the namespaces used by Seam:

Complementing the contextual component model, there are two further basic concepts that facilitate the extreme loose-coupling that is the distinctive feature of Seam applications. The first is a strong event model where events may be mapped to event listeners via JSF-like method binding expressions. The second is the pervasive use of annotations and interceptors to apply cross-cutting concerns to components which implement business logic.

A Seam page action is an event that occurs just before we render a page. We declare page actions in WEB-INF/pages.xml. We can define a page action for either a particular JSF view id:


<pages>
    <page view-id="/hello.xhtml" action="#{helloWorld.sayHello}"/>
</pages>

Or we can use a * wildcard as a suffix to the view-id to specify an action that applies to all view ids that match the pattern:


<pages>
    <page view-id="/hello/*" action="#{helloWorld.sayHello}"/>
</pages>

Keep in mind that if the <page> element is defined in a fine-grained page descriptor, the view-id attribute can be left off since it is implied.

If multiple wildcarded page actions match the current view-id, Seam will call all the actions, in order of least-specific to most-specific.

The page action method can return a JSF outcome. If the outcome is non-null, Seam will use the defined navigation rules to navigate to a view.

Furthermore, the view id mentioned in the <page> element need not correspond to a real JSP or Facelets page! So, we can reproduce the functionality of a traditional action-oriented framework like Struts or WebWork using page actions. This is quite useful if you want to do complex things in response to non-faces requests (for example, HTTP GET requests).

Multiple or conditional page actions my be specified using the <action> tag:


<pages>
    <page view-id="/hello.xhtml">
        <action execute="#{helloWorld.sayHello}" if="#{not validation.failed}"/>
        <action execute="#{hitCount.increment}"/>
    </page>
</pages>

Page actions are executed on both an initial (non-faces) request and a postback (faces) request. If you are using the page action to load data, this operation may conflict with the standard JSF action(s) being executed on a postback. One way to disable the page action is to setup a condition that resolves to true only on an initial request.


<pages>
    <page view-id="/dashboard.xhtml">
        <action execute="#{dashboard.loadData}"
            if="#{not facesContext.renderKit.responseStateManager.isPostback(facesContext)}"/>
    </page>
</pages>

This condition consults the ResponseStateManager#isPostback(FacesContext) to determine if the request is a postback. The ResponseStateManager is accessed using FacesContext.getCurrentInstance().getRenderKit().getResponseStateManager().

To save you from the verbosity of JSF's API, Seam offers a built-in condition that allows you to accomplish the same result with a heck of a lot less typing. You can disable a page action on postback by simply setting the on-postback to false:


<pages>
    <page view-id="/dashboard.xhtml">
        <action execute="#{dashboard.loadData}" on-postback="false"/>
    </page>
</pages>

For backwards compatibility reasons, the default value of the on-postback attribute is true, though likely you will end up using the opposite setting more often.

A JSF faces request (a form submission) encapsulates both an "action" (a method binding) and "parameters" (input value bindings). A page action might also needs parameters!

Since GET requests are bookmarkable, page parameters are passed as human-readable request parameters. (Unlike JSF form inputs, which are anything but!)

You can use page parameters with or without an action method.

Seam lets us provide a value binding that maps a named request parameter to an attribute of a model object.


<pages>
      <page view-id="/hello.xhtml" action="#{helloWorld.sayHello}">
          <param name="firstName" value="#{person.firstName}"/>
          <param name="lastName" value="#{person.lastName}"/>
      </page>
  </pages>

The <param> declaration is bidirectional, just like a value binding for a JSF input:

The essential idea behind all this is that however we get from any other page to /hello.xhtml (or from /hello.xhtml back to /hello.xhtml), the value of the model attribute referred to in the value binding is "remembered", without the need for a conversation (or other server-side state).

If just the name attribute is specified then the request parameter is propagated using the PAGE context (it isn't mapped to model property).


<pages>
      <page view-id="/hello.xhtml" action="#{helloWorld.sayHello}">
          <param name="firstName" />
          <param name="lastName" />
      </page>
  </pages>

Propagation of page parameters is especially useful if you want to build multi-layer master-detail CRUD pages. You can use it to "remember" which view you were previously on (e.g. when pressing the Save button), and which entity you were editing.

This all sounds pretty complex, and you're probably wondering if such an exotic construct is really worth the effort. Actually, the idea is very natural once you "get it". It is definitely worth taking the time to understand this stuff. Page parameters are the most elegant way to propagate state across a non-faces request. They are especially cool for problems like search screens with bookmarkable results pages, where we would like to be able to write our application code to handle both POST and GET requests with the same code. Page parameters eliminate repetitive listing of request parameters in the view definition and make redirects much easier to code.

Rewriting occurs based on rewrite patterns found for views in pages.xml. Seam URL rewriting does both incoming and outgoing URL rewriting based on the same pattern. Here's a simple pattern:



<page view-id="/home.xhtml">
    <rewrite pattern="/home" />
</page>

In this case, any incoming request for /home will be sent to /home.xhtml. More interestingly, any link generated that would normally point to /home.seam will instead be rewritten as /home. Rewrite patterns only match the portion of the URL before the query parameters. So, /home.seam?conversationId=13 and /home.seam?color=red will both be matched by this rewrite rule.

Rewrite rules can take these query paramters into consideration, as shown with the following rules.



<page view-id="/home.xhtml">
    <rewrite pattern="/home/{color}" />
    <rewrite pattern="/home" />
</page>

In this case, an incoming request for /home/red will be served as if it were a request for /home.seam?color=red. Similarly, if color is a page parameter an outgoing URL that would normally show as /home.seam?color=blue would instead be output as /home/blue. Rules are processed in order, so it is important to list more specific rules before more general rules.

Default Seam query parameters can also be mapped using URL rewriting, allowing for another option for hiding Seam's fingerprints. In the following example, /search.seam?conversationId=13 would be written as /search-13.



<page view-id="/search.xhtml">
    <rewrite pattern="/search-{conversationId}" />
    <rewrite pattern="/search" />
</page>

Seam URL rewriting provides simple, bidirectional rewriting on a per-view basis. For more complex rewriting rules that cover non-seam components, Seam applications can continue to use the org.tuckey URLRewriteFilter or apply rewriting rules at the web server.

URL rewriting requires the Seam rewrite filter to be enable. Rewrite filter configuration is discussed in Section 31.1.3.3, “URL rewriting”.

You can specify a JSF converter for complex model properties:


<pages>
   <page view-id="/calculator.xhtml" action="#{calculator.calculate}">
      <param name="x" value="#{calculator.lhs}"/>
      <param name="y" value="#{calculator.rhs}"/>
      <param name="op" converterId="com.my.calculator.OperatorConverter" value="#{calculator.op}"/>
   </page>
</pages>

Alternatively:


<pages>
   <page view-id="/calculator.xhtml" action="#{calculator.calculate}">
      <param name="x" value="#{calculator.lhs}"/>
      <param name="y" value="#{calculator.rhs}"/>
      <param name="op" converter="#{operatorConverter}" value="#{calculator.op}"/>
   </page>
</pages>

JSF validators, and required="true" may also be used:


<pages>
    <page view-id="/blog.xhtml">
        <param name="date" 
               value="#{blog.date}" 
               validatorId="com.my.blog.PastDate" 
               required="true"/>
    </page>
</pages>

Alternatively:


<pages>
    <page view-id="/blog.xhtml">
        <param name="date" 
               value="#{blog.date}" 
               validator="#{pastDateValidator}" 
               required="true"/>
    </page>
</pages>

Even better, model-based Hibernate validator annotations are automatically recognized and validated. Seam also provides a default date converter to convert a string parameter value to a date and back.

When type conversion or validation fails, a global FacesMessage is added to the FacesContext.

You can use standard JSF navigation rules defined in faces-config.xml in a Seam application. However, JSF navigation rules have a number of annoying limitations:

A further problem is that "orchestration" logic gets scattered between pages.xml and faces-config.xml. It's better to unify this logic into pages.xml.

This JSF navigation rule:


<navigation-rule>
   <from-view-id>/editDocument.xhtml</from-view-id>
    
   <navigation-case>
      <from-action>#{documentEditor.update}</from-action>
      <from-outcome>success</from-outcome>
      <to-view-id>/viewDocument.xhtml</to-view-id>
      <redirect/>
   </navigation-case>
    
</navigation-rule>

Can be rewritten as follows:


<page view-id="/editDocument.xhtml">
    
    <navigation from-action="#{documentEditor.update}">
        <rule if-outcome="success">
            <redirect view-id="/viewDocument.xhtml"/>
        </rule>
    </navigation>
    
</page>

But it would be even nicer if we didn't have to pollute our DocumentEditor component with string-valued return values (the JSF outcomes). So Seam lets us write:


<page view-id="/editDocument.xhtml">
    
    <navigation from-action="#{documentEditor.update}" 
                   evaluate="#{documentEditor.errors.size}">
        <rule if-outcome="0">
            <redirect view-id="/viewDocument.xhtml"/>
        </rule>
    </navigation>
    
</page>

Or even:


<page view-id="/editDocument.xhtml">
    
    <navigation from-action="#{documentEditor.update}">
        <rule if="#{documentEditor.errors.empty}">
            <redirect view-id="/viewDocument.xhtml"/>
        </rule>
    </navigation>
    
</page>

The first form evaluates a value binding to determine the outcome value to be used by the subsequent rules. The second approach ignores the outcome and evaluates a value binding for each possible rule.

Of course, when an update succeeds, we probably want to end the current conversation. We can do that like this:


<page view-id="/editDocument.xhtml">
    
    <navigation from-action="#{documentEditor.update}">
        <rule if="#{documentEditor.errors.empty}">
            <end-conversation/>
            <redirect view-id="/viewDocument.xhtml"/>
        </rule>
    </navigation>
    
</page>

As we've ended conversation any subsequent requests won't know which document we are interested in. We can pass the document id as a request parameter which also makes the view bookmarkable:


<page view-id="/editDocument.xhtml">
    
    <navigation from-action="#{documentEditor.update}">
        <rule if="#{documentEditor.errors.empty}">
            <end-conversation/>
            <redirect view-id="/viewDocument.xhtml">
                <param name="documentId" value="#{documentEditor.documentId}"/>
            </redirect>
        </rule>
    </navigation>
    
</page>

Null outcomes are a special case in JSF. The null outcome is interpreted to mean "redisplay the page". The following navigation rule matches any non-null outcome, but not the null outcome:


<page view-id="/editDocument.xhtml">
    
    <navigation from-action="#{documentEditor.update}">
        <rule>
            <render view-id="/viewDocument.xhtml"/>
        </rule>
    </navigation>
    
</page>

If you want to perform navigation when a null outcome occurs, use the following form instead:


<page view-id="/editDocument.xhtml">
    
    <navigation from-action="#{documentEditor.update}">
        <render view-id="/viewDocument.xhtml"/>
    </navigation>
    
</page>

The view-id may be given as a JSF EL expression:


<page view-id="/editDocument.xhtml">

    <navigation>
        <rule if-outcome="success">
            <redirect view-id="/#{userAgent}/displayDocument.xhtml"/>
        </rule>
    </navigation>
    
</page>

Seam components can interact by simply calling each others methods. Stateful components may even implement the observer/observable pattern. But to enable components to interact in a more loosely-coupled fashion than is possible when the components call each others methods directly, Seam provides component-driven events.

We specify event listeners (observers) in components.xml.


<components>
    <event type="hello">
        <action execute="#{helloListener.sayHelloBack}"/>
        <action execute="#{logger.logHello}"/>
    </event>
</components>

Where the event type is just an arbitrary string.

When an event occurs, the actions registered for that event will be called in the order they appear in components.xml. How does a component raise an event? Seam provides a built-in component for this.

@Name("helloWorld")

public class HelloWorld {
    public void sayHello() {
        FacesMessages.instance().add("Hello World!");
        Events.instance().raiseEvent("hello");
    }
}

Or you can use an annotation.

@Name("helloWorld")

public class HelloWorld {
    @RaiseEvent("hello")
    public void sayHello() {
        FacesMessages.instance().add("Hello World!");
    }
}

Notice that this event producer has no dependency upon event consumers. The event listener may now be implemented with absolutely no dependency upon the producer:

@Name("helloListener")

public class HelloListener {
    public void sayHelloBack() {
        FacesMessages.instance().add("Hello to you too!");
    }
}

The method binding defined in components.xml above takes care of mapping the event to the consumer. If you don't like futzing about in the components.xml file, you can use an annotation instead:

@Name("helloListener")

public class HelloListener {
    @Observer("hello")
    public void sayHelloBack() {
        FacesMessages.instance().add("Hello to you too!");
    }
}

You might wonder why I've not mentioned anything about event objects in this discussion. In Seam, there is no need for an event object to propagate state between event producer and listener. State is held in the Seam contexts, and is shared between components. However, if you really want to pass an event object, you can:

@Name("helloWorld")

public class HelloWorld {
    private String name;
    public void sayHello() {
        FacesMessages.instance().add("Hello World, my name is #0.", name);
        Events.instance().raiseEvent("hello", name);
    }
}
@Name("helloListener")

public class HelloListener {
    @Observer("hello")
    public void sayHelloBack(String name) {
        FacesMessages.instance().add("Hello #0!", name);
    }
}

Seam defines a number of built-in events that the application can use to perform special kinds of framework integration. The events are:

Seam components may observe any of these events in just the same way they observe any other component-driven events.

EJB 3.0 introduced a standard interceptor model for session bean components. To add an interceptor to a bean, you need to write a class with a method annotated @AroundInvoke and annotate the bean with an @Interceptors annotation that specifies the name of the interceptor class. For example, the following interceptor checks that the user is logged in before allowing invoking an action listener method:

public class LoggedInInterceptor {


   @AroundInvoke
   public Object checkLoggedIn(InvocationContext invocation) throws Exception {
   
      boolean isLoggedIn = Contexts.getSessionContext().get("loggedIn")!=null;
      if (isLoggedIn) {
         //the user is already logged in
         return invocation.proceed();
      }
      else {
         //the user is not logged in, fwd to login page
         return "login";
      }
   }
}

To apply this interceptor to a session bean which acts as an action listener, we must annotate the session bean @Interceptors(LoggedInInterceptor.class). This is a somewhat ugly annotation. Seam builds upon the interceptor framework in EJB3 by allowing you to use @Interceptors as a meta-annotation for class level interceptors (those annotated @Target(TYPE)). In our example, we would create an @LoggedIn annotation, as follows:

@Target(TYPE)

@Retention(RUNTIME)
@Interceptors(LoggedInInterceptor.class)
public @interface LoggedIn {}

We can now simply annotate our action listener bean with @LoggedIn to apply the interceptor.

@Stateless

@Name("changePasswordAction")
@LoggedIn
@Interceptors(SeamInterceptor.class)
public class ChangePasswordAction implements ChangePassword { 
    
    ...
    
    public String changePassword() { ... }
    
}

If interceptor ordering is important (it usually is), you can add @Interceptor annotations to your interceptor classes to specify a partial order of interceptors.

@Interceptor(around={BijectionInterceptor.class,

                     ValidationInterceptor.class,
                     ConversationInterceptor.class},
             within=RemoveInterceptor.class)
public class LoggedInInterceptor
{
    ...
}

You can even have a "client-side" interceptor, that runs around any of the built-in functionality of EJB3:

@Interceptor(type=CLIENT)

public class LoggedInInterceptor
{
    ...
}

EJB interceptors are stateful, with a lifecycle that is the same as the component they intercept. For interceptors which do not need to maintain state, Seam lets you get a performance optimization by specifying @Interceptor(stateless=true).

Much of the functionality of Seam is implemented as a set of built-in Seam interceptors, including the interceptors named in the previous example. You don't have to explicitly specify these interceptors by annotating your components; they exist for all interceptable Seam components.

You can even use Seam interceptors with JavaBean components, not just EJB3 beans!

EJB defines interception not only for business methods (using @AroundInvoke), but also for the lifecycle methods @PostConstruct, @PreDestroy, @PrePassivate and @PostActive. Seam supports all these lifecycle methods on both component and interceptor not only for EJB3 beans, but also for JavaBean components (except @PreDestroy which is not meaningful for JavaBean components).

JSF is surprisingly limited when it comes to exception handling. As a partial workaround for this problem, Seam lets you define how a particular class of exception is to be treated by annotating the exception class, or declaring the exception class in an XML file. This facility is meant to be combined with the EJB 3.0-standard @ApplicationException annotation which specifies whether the exception should cause a transaction rollback.

Since we can't add annotations to all the exception classes we are interested in, Seam also lets us specify this functionality in pages.xml.


<pages>
   
   <exception class="javax.persistence.EntityNotFoundException">
      <http-error error-code="404"/>
   </exception>
   
   <exception class="javax.persistence.PersistenceException">
      <end-conversation/>
      <redirect view-id="/error.xhtml">
          <message>Database access failed</message>
      </redirect>
   </exception>
   
   <exception>
      <end-conversation/>
      <redirect view-id="/error.xhtml">
          <message>Unexpected failure</message>
      </redirect>
   </exception>
   
</pages>

The last <exception> declaration does not specify a class, and is a catch-all for any exception for which handling is not otherwise specified via annotations or in pages.xml.

You can also use EL to specify the view-id to redirect to.

You can also access the handled exception instance through EL, Seam places it in the conversation context, e.g. to access the message of the exception:


...
throw new AuthorizationException("You are not allowed to do this!");

<pages>

    <exception class="org.jboss.seam.security.AuthorizationException">
        <end-conversation/>
        <redirect view-id="/error.xhtml">
            <message severity="WARN">#{org.jboss.seam.handledException.message}</message>
        </redirect>
    </exception>

</pages>

org.jboss.seam.handledException holds the nested exception that was actually handled by an exception handler. The outermost (wrapper) exception is also available, as org.jboss.seam.caughtException.

If you are using JPA:


<exception class="javax.persistence.EntityNotFoundException">
   <redirect view-id="/error.xhtml">
      <message>Not found</message>
   </redirect>
</exception>

<exception class="javax.persistence.OptimisticLockException">
   <end-conversation/>
   <redirect view-id="/error.xhtml">
      <message>Another user changed the same data, please try again</message>
   </redirect>
</exception>

If you are using the Seam Application Framework:


<exception class="org.jboss.seam.framework.EntityNotFoundException">
   <redirect view-id="/error.xhtml">
      <message>Not found</message>
   </redirect>
</exception>

If you are using Seam Security:


<exception class="org.jboss.seam.security.AuthorizationException">
   <redirect>
      <message>You don't have permission to do this</message>
   </redirect>
</exception>
    
<exception class="org.jboss.seam.security.NotLoggedInException">
   <redirect view-id="/login.xhtml">
      <message>Please log in first</message>
   </redirect>
</exception>

And, for JSF:


<exception class="javax.faces.application.ViewExpiredException">
   <redirect view-id="/error.xhtml">
      <message>Your session has timed out, please try again</message>
   </redirect>
</exception>

A ViewExpiredException occurs if the user posts back to a page once their session has expired. The conversation-required and no-conversation-view-id settings in the Seam page descriptor, discussed in Section 8.4, “Requiring a long-running conversation”, give you finer-grained control over session expiration if you are accessing a page used within a conversation.

It's time to understand Seam's conversation model in more detail.

Historically, the notion of a Seam "conversation" came about as a merger of three different ideas:

  • The idea of a workspace, which I encountered in a project for the Victorian government in 2002. In this project I was forced to implement workspace management on top of Struts, an experience I pray never to repeat.

  • The idea of an application transaction with optimistic semantics, and the realization that existing frameworks based around a stateless architecture could not provide effective management of extended persistence contexts. (The Hibernate team is truly fed up with copping the blame for LazyInitializationExceptions, which are not really Hibernate's fault, but rather the fault of the extremely limiting persistence context model supported by stateless architectures such as the Spring framework or the traditional stateless session facade (anti)pattern in J2EE.)

  • The idea of a workflow task.

By unifying these ideas and providing deep support in the framework, we have a powerful construct that lets us build richer and more efficient applications with less code than before.

The examples we have seen so far make use of a very simple conversation model that follows these rules:

Seam transparently propagates the conversation context (including the temporary conversation context) across JSF postbacks and redirects. If you don't do anything special, a non-faces request (a GET request for example) will not propagate the conversation context and will be processed in a new temporary conversation. This is usually - but not always - the desired behavior.

If you want to propagate a Seam conversation across a non-faces request, you need to explicitly code the Seam conversation id as a request parameter:


<a href="main.jsf?#{manager.conversationIdParameter}=#{conversation.id}">Continue</a>

Or, the more JSF-ish:


<h:outputLink value="main.jsf">
    <f:param name="#{manager.conversationIdParameter}" value="#{conversation.id}"/>
    <h:outputText value="Continue"/>
</h:outputLink>

If you use the Seam tag library, this is equivalent:


<h:outputLink value="main.jsf">
    <s:conversationId/>
    <h:outputText value="Continue"/>
</h:outputLink>

If you wish to disable propagation of the conversation context for a postback, a similar trick is used:


<h:commandLink action="main" value="Exit">
    <f:param name="conversationPropagation" value="none"/>
</h:commandLink>

If you use the Seam tag library, this is equivalent:


<h:commandLink action="main" value="Exit">
    <s:conversationPropagation type="none"/>
</h:commandLink>

Note that disabling conversation context propagation is absolutely not the same thing as ending the conversation.

The conversationPropagation request parameter, or the <s:conversationPropagation> tag may even be used to begin a conversation, end the current conversation, destroy the entire conversation stack, or begin a nested conversation.


<h:commandLink action="main" value="Exit">
    <s:conversationPropagation type="end"/>
</h:commandLink>

<h:commandLink action="main" value="Exit">
    <s:conversationPropagation type="endRoot"/>
</h:commandLink>

<h:commandLink action="main" value="Select Child">
    <s:conversationPropagation type="nested"/>
</h:commandLink>

<h:commandLink action="main" value="Select Hotel">
    <s:conversationPropagation type="begin"/>
</h:commandLink>

<h:commandLink action="main" value="Select Hotel">
    <s:conversationPropagation type="join"/>
</h:commandLink>

This conversation model makes it easy to build applications which behave correctly with respect to multi-window operation. For many applications, this is all that is needed. Some complex applications have either or both of the following additional requirements:

A nested conversation is created by invoking a method marked @Begin(nested=true) inside the scope of an existing conversation. A nested conversation has its own conversation context, but can read values from the outer conversation's context. The outer conversation's context is read-only within a nested conversation, but because objects are obtained by reference, changes to the objects themselves will be reflected in the outer context.

When an @End is subsequently encountered, the nested conversation will be destroyed, and the outer conversation will resume, by "popping" the conversation stack. Conversations may be nested to any arbitrary depth.

Certain user activity (workspace management, or the back button) can cause the outer conversation to be resumed before the inner conversation is ended. In this case it is possible to have multiple concurrent nested conversations belonging to the same outer conversation. If the outer conversation ends before a nested conversation ends, Seam destroys all nested conversation contexts along with the outer context.

The conversation at the bottom of the conversation stack is the root conversation. Destroying this conversation always destroy all of its descendents. You can achieve this declaratively by specifying @End(root=true).

A conversation may be thought of as a continuable state. Nested conversations allow the application to capture a consistent continuable state at various points in a user interaction, thus ensuring truly correct behavior in the face of backbuttoning and workspace management.

As mentioned previously, if a component exists in a parent conversation of the current nested conversation, the nested conversation will use the same instance. Occasionally, it is useful to have a different instance in each nested conversation, so that the component instance that exists in the parent conversation is invisible to its child conversations. You can achieve this behavior by annotating the component @PerNestedConversation.

JSF does not define any kind of action listener that is triggered when a page is accessed via a non-faces request (for example, a HTTP GET request). This can occur if the user bookmarks the page, or if we navigate to the page via an <h:outputLink>.

Sometimes we want to begin a conversation immediately the page is accessed. Since there is no JSF action method, we can't solve the problem in the usual way, by annotating the action with @Begin.

A further problem arises if the page needs some state to be fetched into a context variable. We've already seen two ways to solve this problem. If that state is held in a Seam component, we can fetch the state in a @Create method. If not, we can define a @Factory method for the context variable.

If none of these options works for you, Seam lets you define a page action in the pages.xml file.


<pages>
    <page view-id="/messageList.xhtml" action="#{messageManager.list}"/>
    ...
</pages>

This action method is called at the beginning of the render response phase, any time the page is about to be rendered. If a page action returns a non-null outcome, Seam will process any appropriate JSF and Seam navigation rules, possibly resulting in a completely different page being rendered.

If all you want to do before rendering the page is begin a conversation, you could use a built-in action method that does just that:


<pages>
    <page view-id="/messageList.xhtml" action="#{conversation.begin}"/>
    ...
</pages>

Note that you can also call this built-in action from a JSF control, and, similarly, you can use #{conversation.end} to end conversations.

If you want more control, to join existing conversations or begin a nested conversion, to begin a pageflow or an atomic conversation, you should use the <begin-conversation> element.


<pages>
    <page view-id="/messageList.xhtml">
       <begin-conversation nested="true" pageflow="AddItem"/>
    <page>
    ...
</pages>

There is also an <end-conversation> element.


<pages>
    <page view-id="/home.xhtml">
       <end-conversation/>
    <page>
    ...
</pages>

To solve the first problem, we now have five options: