Seam
Seam UI
By Jacob Orshalick
12,797 Downloads · Refcard 42 of 151 (see them all)
Download
FREE PDF
The Essential Seam UI Cheat Sheet
Seam UI
ABOUT Seam UI
Seam is a next generation web framework that integrates standard Java EE technologies with a wide variety of nonstandard technologies into a consistent, unified, programming model. Seam drove the development of Web Beans (JSR-299) and continues to develop innovations that are changing the face of web development as well as Java EE technologies. If you haven't taken a look at Seam, I suggest you do.
As you develop Seam applications, you'll find this reference a handy guide for understanding how Seam simplifies JSF development. This reference does not cover all of what Seam provides, but covers the most commonly used UI annotations and XML elements as of Seam 2.1.
Simplifying jsf
While Seam is no longer limited to JSF as it's view layer, one of the framework's initial goals was simplifying JSF development. Seam plugs into the JSF lifecycle to provide a number of enhancements including:
- Direct Facelets support (https://facelets.dev.java.net/)
- n A unified component model
- n Additional contexts including conversations
- n Bean validations
- n A component event model
- n Exception handling
- n RESTful URLs
- n Extended EL support
- n And much more...
Page Navigation
Page navigation with JSF can be verbose and only provides a limited feature set. Seam provides a concise navigation language that incorporates conversation management, security, exception handling, request parameters, event notification, and more. Here we will discuss the pages namespace which defines the navigation flow of a Seam application as well as the navigation namespace for configuring the navigation components.
The Pages Namespace
Schema URI
http://jboss.com/products/seam/pages
Schema XSD
http://jboss.com/products/seam/pages-2.1.xsd
The pages namespace is used to define the WEB-INF/pages. xml definition. The pages.xml file unifies navigation logic
Page Navigation, continued
with Seam "orchestration” logic. This logic includes page parameters, conversation management, and allows navigation to be based on evaluation of arbitrary EL expressions instead of relying on return values. In addition, event notification is possible, generic exception handling, security restrictions, etc.
Seam XML Diagram Key
The Seam XML diagrams use the following notations to indicate required elements, cardinality, and containment:
Pages Namespace Elements
| Element | Description |
| <pages> | Root element defining general configuation applied to all pages. |
| <page> | Defines the navigation as well as "orchestration” logic associated with a view-id. |
Page Navigation, continued
| <conversation> | Configures a named natural conversation. |
| <exception> | Defines handling for a specific type of exception. |
| <http-error> | Specifies an HTTP error code to be returned to the user. |
| <message> | Specifies a message that should be displayed to the user. |
| <restrict> | Configures a security restriction for a page defined through EL. |
| <description> | Provides a description for a page that will be displayed in the ConversationSwitcher. Note that without this description the conversation will not show up in this component. |
| <param> | Defines a page parameter to be set from a GET request query parameter into a component. |
| <action> | Defines an action to be executed as a method-binding expression. |
| <header> | Specifies HTTP headers to be added to a page. |
| <navigation> | Defines the navigation rules associated with a page. |
| <rule> | Specifies a specific action outcome or boolean value-binding expression under which navigation should occur. |
| <redirect> | Redirects the user to the specified view-id. |
| <render> | Specifies a view-id to be rendered. |
| <raise-event> | Configures an event to be raised on page display or navigation. |
| <beginconversation> | Begins a long-running conversation either on access of a page or on navigation. |
| <endconversation> | Ends a long runing conversation either on access of a page, on navigation, or on occurrence of an exception. |
Pages Namespace Examples
Defining Navigation Rules
The following example defines a few pages with some simple navigation rules based on the execution of EL expressions:
| Pages Namespace Examples |
|
When a hotel is selected on the /main.xhtml view and the selectHotel method is invoked, we begin a long-running conversation and the user is redirected to the /hotelxhtml view. A user is required to be logged in to access /main. xhtml. If the user is not logged in, he or she will be redirected
to the login-view-id, or /home.xhtml in this case. The /rewards.xhtml page is further restricted to users with the REWARDS role. The s:hasRole EL function throws an
Page Navigation, continued
AuthorizationException if the user is not authorized thereby ending the conversation and sending the user to the error page with an appropriate message.
Using Page Parameters and Natural Conversations
The following example defines a natural conversation named Booking. The parameter-name and parameter-value define
the parameter that will be using to uniquely identify a conversation instance. You must ensure that the EL expression
evaluates to a value when the conversation is initialized.
| Using page Parameters and Natural Conversations |
|
Each of the pages defined participate in the natural conversation by specifying Booking as the conversation attribute. The /hotel.xhtml page begins the natural conversation by loading the current hotel according to the value of the hotelId param. This param is initialized from a request query parameter: http://seam-booking-example/ hotel.seam?hotelId=10. The hotelBooking action then uses this parameter value to initialize the hotel in the conversation context through an @Factory method.
Note that all pages other than /hotel.xhtml specify conversation-required=”true”. This ensures that should a user attempt to access one of these pages outside the context of a long-runningconversation, the user will be redirected to the no-conversation-view-id defined in the <pages> tag.
Navigation Namespace
Schema URI
http://jboss.com/products/seam/navigation
Schema XSD
http://jboss.com/products/seam/navigation-2.1.xsd
The navigation namespace provides the ability to externalize configuration of the Pages component from the pages.xml file and override the location of pages configuration files.
Navigation Namespace Diagram

Page Navigation, continued
Navigation Namespace Elements
| Element | Description |
| <navigation:pages> | Configures the Pages component which drives navigation based on the /WEB-INF/pages.xml file. |
| <navigation:resources> | Allows you to specify a list of pages configuration files. Setting this value overrides the default /WEB-INF/ pages.xml. |
Navigation Namespace Example
Below is an example of <navigation:pages> definition:
| Navigation Namespace Example |
|
The ports have now been defined for both HTTP and HTTPS. In addition, if a page has been configured as conversationrequired=” true”, the user will be redirected to /main.xhtml if a long-running conversation is not in progress. The loginview- id specifies that the user should be redirected to /home. xhtml if a login is required by a page definition and the user has not yet logged in.
JSF component annotations
The definition of components found in a typical JSF application is simple when using Seam. Data models, converters, and validators can be defined quickly with no XML configuration required through use of component annotations.
Datamodel Annotations
The following annotations simplify display of a clickable <h:dataTable> in JSF backed by a DataModel by directly binding a Collection to action attributes.
| Annotation | Use | Description |
| @DataModel | Field, Method |
Turns the annotated field or getter method into a JSF DataModel object, and implies the @Out annotation. Can be used with a List, Map, or Set. |
| @DataModelSelection | Field, Method |
Injects the user's @DataModel selection. The actual object instance selected is injected. |
| @DataModelSelectionIndex | Field, Method |
Injects the row index of the user's @DataModel selection. |
Conversion and Validation Annotations
The following annotations allow you to quickly define Seam components as custom JSF converters and validators
| Annotation | Use | Description |
| @Converter | Type | Allows a Seam component to act as a JSF converter. The annotated class must be a Seam component, and must implement: javax.faces.convertConverter |
| @Validator | Type | Allows a Seam component to act as a JSF validator. The annotated class must be a Seam component, and must implement: javax.faces.validator.Validator |
Jsf Component tags
An extended JSF tag library is defined by Seam to provide control over conversational navigation, simplified dropdowns, bean validation, and component formatting.
Integrating the Seam Taglib
Taglib URI
http://jboss.com/products/seam/taglib
Taglib Declaration
| Facelets | <html xmlns=”http://www.w3.org/1999/xhtml” xmlns:s=”http://jboss.com/products/seam/taglib”> |
| JSP | <%@ taglib uri=”http://jboss.com/products/seam/taglib” prefix=”s” %> |
Controlling Navigation
Seam provides a set of JSF components for controlling conversation propagation across both GET and POST requests. These components also extend the capabilities of JSF to allow GET requests to trigger actions and make it simple to define default page actions.
Navigation Tags
| Tag | Description |
| <s:link> | Link that performs a GET request to invoke an action and allows conversation propagation to be controlled. |
| <s:button> | Button that performs a GET request to invoke an action and allows conversation propagation to be controlled. |
| <s:conversationId> | Adds the conversation ID to a JSF link or button, especially useful with the |
| <s:conversation Propagation> | Allows the conversation propagation to be controlled for a JSF command link or command button. |
| <s:defaultAction> | Configures a button (e.g.<h:commandButton>) as the default action when the form is submitted using the enter key |
Navigation Examples
The conversation propagation can be controlled from a link through use of the
| Navigation Examples |
| <s:link view-id=”/main.xhtml” propagation=”none” value=”Back to Main” /> |
We can also trigger an action during an HTTP GET request:
| Navigation Examples |
/td>
|
The <s:link> component has richer conversation-management capabilities than the plain JSF <commandbutton>, which simply propagates the conversation context between pages.

JSF Component Tags, continued
What if you want to exit, begin, or end a conversation context from a button click? The following example shows a button that exits the current conversation context.
| Navigation Examples |
|
In addition, by specifying the button is the <s:defaultAction/> the user is returned to /main.xhtml through a navigation rule should the user submit the form by pressing the enter key.

Dropdown Selection
When developing JSF pages it is commonly required to associate the possible selections of a dropdown component with a list of objects or an enumeration of values. Unfortunately with standard JSF this requires quite a bit of glue code to achieve. Seam makes this simple through the <s:selectItems> and <s:enumItem> tags. Even further when the<s:convertEntity> and the <s:selectItems> tags are combined, you can directly associate JPA or Hibernate managed entities by simply binding a dropdown component to an entity association attribute.
Dropdown Tags
| Tag | Description |
| <s:convertEntity> | Converts a managed entity to and from its unique identifier. Used for selecting entities in a dropdown component. |
| <s:convertEnum> | Converts an enum to and from its constant representation. Generally used for selecting enums in a dropdown component. |
| <s:enumItem> | Creates a SelectItem from an enum value allowing the label to be specified. |
| <s:selectItems> | Creates a List<SelectItem> from a List, Set, DataModel or Array. Iterates over the Collection with a var allowing the itemLabel and itemValue to be defined through EL. |
Dropdown Examples
The following example demonstrates directly associating a managed entity from a List of entities. The CreditCard class represents types of credit cards and the @NamedQuery allows us to load all CreditCard types from the data store.
| Dropdown Examples |
|
JSF Component Tags, continued
The Booking class is then be defined with a @ManyToOne reference to the CreditCard entity.
| Dropdown Examples |
|
In order to load the list of credit card types, the Booking Action can define an @Factory method which initializes the list of CreditCard entities in the conversation context.
| Dropdown Examples |
|
The method simply uses the named query we defined previously to load the entities from the current Entity- Manager instance. Note that our Seam-managed Persistence Context (SMPC) is named entityManager. If your SMPC is named something other than entityManager, you will have to configure the EntityConverter in components.xml (see the UI Namespace).
Finally, we can define a JSF<h:selectOneMenu> component which simply binds directly to the creditCard attribute of the current booking instance.
| Dropdown Examples |
<h:selectOneMenu id=”creditCard”
value=”#{booking.creditCard}” required=”true”>
<s:selectItems noSelectionLabel=””
var=”type” value=”#{creditCardTypes}”
itemLabel=”#{type.description}” />
<s:convertEntity />
</h:selectOneMenu>
|
The #{creditCardTypes} are loaded into the conversation context from the @Factory method we defined previously. The <s:selectItems> component allows us to iterate over the list of CreditCard entities and display the description by referencing the type variable. The <s:convertEntity> tag ensures that the user selection is converted to an entity for association with the booking instance.
Simplifying Validation
When using Seam you can define validations directly on your entity beans that behave like JSF validators. These bean validators are provided by the Hibernate Validator framework
JSF Component Tags, continued
(http://validatior.hibernate.org), but with Seam can be triggered as JSF validations.
Validation Tags
| Tag | Description |
| <s:validate> | Triggers entity bean validations for the tagged component on a form submission. |
| <s:validateAll> | Triggers entity bean validations for all components embedded within this tag on a form submission. |
Validation Examples
The Seam Booking example allows a user to enter her credit card number while booking a hotel. Credit card numbers have a common pattern and should be validated on input. The following example demonstrates how we can apply these restrictions using Hibernate Validator annotations:
| Validation Examples |
|
The @Length annotation restricts the String length to 16 characters while the @Pattern annotation specifies a regular expression restricting the String to digits only. Once these annotations are added to the entity, we can trigger them as validations during the JSF validations phase. Simply embedding the <s:validate> tag within the <h:inputText> component ensures the validation is triggered. If an invalid credit card number is input, the user will be presented with the message defined in the annotation.
| Validation Examples |
|

Formatting
While validation becomes simple with Seam, standard JSF validation messages are not very flexible. Although you can
JSF Component Tags, continued
assign CSS classes to customize the look of the error message itself, you cannot alter the appearance of the input field that contains the invalid input. The following formatting tags allow you to decorate invalid fields with styles and messages. In addition to validation message formatting Seam provides formatting components for applying labels directly to JSF input fields, optionally rendering HTML <div> and <span> tags, and optionally rendering page fragments.
| Tag | Description |
| <s:decorate> | "Decorate” a JSF input field when validation fails or when required=”true” is set using a Facelets template. |
| <s:label> | "Decorate” a JSF input field with the label. The label is placed inside the HTML <label> tag, and is associated with the nearest JSF input component. |
| <s:message> | "Decorate” a JSF input field with the validation error message associated with that field. |
| <s:div> | Render an HTML <div>. Allows the <div> to be optionally rendered through the rendered attribute. |
| <s:span> | Render an HTML <span>. Allows the <span> to be optionally rendered through the rendered attribute. |
| <s:fragment> | A non-rendering component useful for optionally rendering its children through the rendered attribute. |
Formatting Examples
To use a Seam decorator, you first define how the decorator behaves using special named JSF facets. The beforeInvalidField facet defines what to display in front of the invalid field; the afterInvalidField facet defines what to display after the invalid field, and the <s:message> tag shows the error message for the input field; and the aroundInvalidField facet defines a span or div element that encloses the invalid field and the error message. You also can use the aroundField facet to decorate the appearance of valid (or initial) input fields.
Formatting Examples
To use a Seam decorator, you first define how the decorator behaves using special named JSF facets. The beforeInvalidField facet defines what to display in front of the invalid field; the afterInvalidField facet defines what to display after the invalid field, and the <s:message> tag shows the error message for the input field; and the aroundInvalidField facet defines a span or div element that encloses the invalid field and the error message. You also can use the aroundField facet to decorate the appearance of valid (or initial) input fields.
| Formatting Examples |
Now you can simply enclose each input field in a pair of <s:decorate> tags as shown below:
| Formatting Examples |
|
The UI Namespace
Schema URI
http://jboss.com/products/seam/ui
Schema XSD
http://jboss.com/products/seam/ui-2.1.xsd
As you have seen, the <s:convertEntity/> tag provides the ability to convert entities to and from dropdown selections. In most cases this is as simple as defining <s:convertEntity> within the dropdown, but there are cases where this needs to be customized. The UI namespace allows you to configure
JSF Component Tags, continued
the EntityConverter component in the following cases:
JPA is the persistence provider and your Seam-Managed Persistence Context (SMPC) is named something other than EntityManager Hibernate is being used directly as the persistence provider You would like to use more than one EntityManager with the EntityConverter
In each of these cases, it is necessary to configure the Entity-Converter component using the UI namespace.
UI Namespace Diagram
UI Namespace Elements
| Tag | Description |
| <ui:entityconverter> | Allows a custom EntityConverter to be defined which is useful if more than one EntityManager is being used. |
| <ui:jpa-entityloader> | Configures a Seam-Managed Persistence Context (SMPC) named something other than entityManager. |
| <ui:hibernateentity-loader> | Allows a Managed Hibernate Session to be configured for use with the EntityConverter. By default assumes the component name session. |
JSF Component Tags, continued
UI Namespace Examples
The following example configures the EntityConverter with a custom EntityManager name:
| UI Namespace Examples |
|
As you can see, the Seam-managed Persistence Context is given the name em. This is simply referenced through an EL expression in the jpa-entity-loader configuration.
Core Seam
By Jacob Orshalick
15,397 Downloads · Refcard 31 of 151 (see them all)
Download
FREE PDF
The Essential Seam Cheat Sheet
Core Seam
About SEAM
Seam is a next generation web framework that integrates standard Java EE technologies with a wide variety of nonstandard technologies into a consistent, unified, programming model. Seam drove the development of the Web Beans specification (JSR-299) and continues to develop innovations that are changing the face of web development as well as Java EE technologies. If you haven't taken a look at Seam, I suggest you do.
As you develop Seam applications, you'll find this quick referencea handy guide for understanding core concepts, configuration, and tool usage. This quick reference is not intended to cover all of what Seam provides, but will cover the most commonly used annotations and XML elements as of Seam 2.1. In addition, this guide will point you to examples distributed with Seam to see real examples of how the configuration options can be used in practice.
Dependency Injection In A Nutshell
Dependency injection is an inversion of control technique that forms the core of modern-day frameworks. Traditionally objects have held the responsibility for obtaining references to the objects they collaborate with. These objects are extroverted as they reach out to get their dependencies. This leads to tight coupling and hard to test code.
Dependency injection allows us to create introverted objects. The objects dependencies are injected by a container or by some external object (e.g. a test class). Bijection is described by the following formula:
dependency injection + context = bijection
With bijection, when dependencies are injected context counts! Dependencies are injected prior to each component method invocation. In addition, components can contribute to the context by outjecting values

As you can see the HotelBookingAction is scoped to and executes within a context. This behavior allows us to quit worrying about shuffling values into and out of contexts like the HttpSession, allows components to hold state, and unifies the component model across application tiers.
Contextual Components
When a method is invoked on a component, its dependencies are injected from the current context. Seam performs a context lookup in the following order of precedence: Event Scope, Page Scope, Conversation Scope, Session Scope, Business Scope, Application Scope.
Component Annotations
Component Definition Annotations
In order for your Seam components to take advantage of bijection, you must register them with the Seam container. Registering your component with Seam is as simple as annotating it with @Name. The following annotations will register your component and define its lifecycle.
| Annotation | Use | Description |
| @Name | Type | Declares a Seam component by name. The component is registered with Seam and can be referenced by name through Expression Language (EL), injection, or a context lookup. |
| @Scope | Type | Defines the scope (or context) the Seam component will be placed into by the container when created. |
| @AutoCreate | Type | Specifies that a component should be created when being injected if not available in the current context. |
| @Startup | Type | Indicates that an application scoped component should be created when the application is initialized or that a session component should be created when a session is started. Not valid for any other contexts. |
| @Install | Type | Declares whether a Seam component should be installed based on availability of dependencies or precedence. |
| @Role | Type | Defines an additional name and scope associated with the component. The @Roles annotation allows definition of multiple roles. |
Component Bijection Annotations: Once you have defined a component, you can specify the dependencies of your component and what the component contributes back to the context.
| Annotation | Use | Description |
| @In | Field, Method | Declares a dependency that will be injected from the context, according to context precedence, prior to a method invocation. Note that these attributes will be disinjected (or set to null) after the invocation completes. |
| @Out | Field, Method | Declares a value that will be outjected after a method invocation to the context of the component (implicit) or a specified context (explicit). |
Component Lifecycle Annotations: The following annotations allow you to control the lifecycle of a component either by reacting to events or wrapping the component entirely.
| Annotation | Use | Description |
| @Create | Method | Declares that a method should be called after component instantiation. |
| @Destroy | Method | Declares that a method should be called just before component destruction. |
| @Factory | Method | Marks a method as a factory method for a context variable. A factory method is called whenever no value is bound to the named context variable and either initializes and outjects the value or simply returns the value to the context. |
| @Unwrap | Method | Declares that the object returned by the annotated getter method is to be injected instead of the component itself. Referred to as the "manager component" pattern. |
Component Events Annotations: Through Seam's event model, components can raise events or listen for events raised by other components through simple annotation. In addition, Seam defines a number of built-in events that the application can use to perform special kinds of framework integration (see http://seamframework.org/Documentation, Contextual Events).
| Annotation | Use | Description |
| @RaiseEvent | Method | Declares that a named event should be raised after the method returns a non-null result without exception. |
| @Observer | Method | Declares that a method should be invoked on occurrence of a named event or multiple named events. |
The Components Namespace
Schema URI
http://jboss.com/products/seam/components
Schema XSD
http://jboss.com/products/seam/components-2.1.xsd
So far we've seen how components can be declared using annotations. In most cases this is the preferred approach, but there are some situations when component definition through annotations is not an option:
- when a class from a library outside of your control is to be exposed as a component
- when the same class is being configured as multiple components
In addition, you may want to configure values into a component that could change by environment, e.g. ip-addresses, ports, etc. In any of these cases, we can use XML to configure the component through the components namespace.
Seam XML Diagram Key
The Seam XML diagrams use the following notations to indicate required elements, cardinality, and containment:
![]()
Components Namespace Diagram

Components Namespace Elements
| Element | Description |
| <component> | Defines a component in the Seam container. |
| <event> | Specifies an event type and the actions to execute on occurrence of the event. |
| <factory> | 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. Generally used for aliasing. |
| <import> | Specifies component namespaces that should be imported globally which allows referencing by unqualified component names. Specified by package. |
| <action> | Specifies an action to execute through a method binding expression. |
| <property> | Injects a value or reference into a Seam component. Can use a value or method binding expression to inject components. |
| <key> | Defines the key for the following value when defining a map. |
| <value> | For list values, the value to be added. For map values, the value for the preceding key. |
Component Element Attributes: The attributes of the component element are synonymous with component definition through annotations.
| Element | Description |
| name | Declares a component by name; synonymous with @Name. |
| class | References the Java class of the component implementation. |
| scope | Defines the scope (or context) the Seam component will be placed into by the container when created. |
| precedence | Precedence is used when a name-clash is found between two components (higher precedence wins). |
| installed | Boolean indicating whether the component should be installed. |
| auto-create | Specifies that a component should be created when being injected if not available in the current context. |
| startup | Indicates that an application scoped component should be created when the application is initialized or that a session component should be created when a session is started. Not valid for any other contexts. |
| startupDepends | A list of other application scope components that should be started before this one, if they are installed. |
| jndi-name | EJB components only. The JNDI name used to lookup the component. Only used with EJB components that don't follow the global JNDI pattern. |
| Components Namespace Example |
| The following examples demonstrate how component configuration is possible with Seam. The hotelBooking component is configured for injection of a paymentService instance. |
|
| Note that we specified a name and class for the PaymentServiceClient instances. This is required as the PaymentServiceClient is a library implementation. The name is always required, but the class can be omitted if you are simply configuring the values of a component with an @Name annotation as shown with the hotelBooking. The scope is restricted to the scopes provided by Seam; here we use APPLICATION. |
| Simplify your component configuration through use of namespaces. |
|
Seam makes this quite simple through use of the @Namespace annotation. Just create a file named package-info.java in the package where your components live:
|
|
Now we can reference the namespace in our components.xml:
|
| Note that component names and attribute names are specified in hyphenated form when using namespaces. To gain the benefits of auto-completion and validation, a schema can also be created to represent your components. A custom schema can import the components namespace to reuse the defined component types. |
Rapid Application Development
Seam-gen is a rapid application generator shipped with the Seam distribution. With a few command line commands, seam-gen generates an array of artifacts for Seam projects to help you get started. In particular, seam-gen is useful for the following.
- Automatically generate an empty Seam project with common configuration files, a build script, and directories for Java code and JSF view pages.
- Automatically generate complete Eclipse and NetBeans project files for the Seam project.
- Reverse-engineer entity bean objects from relational database tables.
- Generate template files for common Seam components.
Seam-gen Commands
Seam-gen command should be executed in the directory of your Seam distribution. To get started execute the seam setup command. Each command provides useful prompts that will guide you through the configuration specifics.
| Command | Description |
| seam setup | Configures seam-gen for your environment: JBoss AS installation directory, Eclipse workspace, and database connection. |
| seam new-project | Creates a new deployable Seam project based on the configuration settings provided in the setup. |
| seam -D[profile] deploy | Deploys the new project you've created with the configuration specific to the [profile] specified, i.e. dev, test, or prod. |
| seam new-action | Creates a simple web page with a stateless action method. Generates a facelets page and component for your project. |
| seam new-form | Creates a form with an action. |
| seam generate-entities | Generates an application from an existing database. Simply ensure that your setup points to the appropriate database. |
| seam generate-ui | Generates an application from existing JPA/EJB3 entities placed into the src/model folder |
| seam restart | Restarts the application on the server instance |
Seam-gen Source Directories
The source directories created by seam-gen are each dedicated to holding certain types of source files. This enables seam-gen to determine what tests need to be executed as well as selectively hot-deploy your Seam components.
| /src/main | Classes to include in the main (static) classpath. |
| /src/hot | Classes to include in the hot deployable classpath when running in development mode (see the Hot Tip below). |
| /src/test | Test classes should be placed in this source folder. These classes will not be deployed but will be executed as part of the test target. |
Seam-gen Profiles
Seam-gen supports the concept of "profile". The idea is that the application probably needs different settings (e.g. database settings, etc) in the development, test, and production phases. So, the project provides alternative configuration files for each of the three scenarios. In the resources directory, you will find the following configuration files:
| /META-INF/persistence-*.xml | Provides configuration of a JPA persistence-unit for each environment. |
| import-*.sql | Imports data into a generated schema based on deployment environment. Generally useful for testing purposes |
| components-*.properties | Allows wild-card replacement of Seam component properties based on environment (see Hot Tip in the Core Namespace for more information). |

Conversation Management
The Conversation Model in a Nutshell
The conversation model is the core of Seam. It provides the basis of context management in Seam applications. A session holds potentially many concurrent conversations with a user, each tied to its own unit of work with its own context.

On every user request a temporary conversation is created or a long-running conversation is resumed. A conversation is resumed when a valid conversation-id (cid) is sent with the request.

* Note that the filled circle indicates the initial state, while the hollow circle containing a smaller filled circle indicates an end state.
| Temporary Conversations | A temporary conversation is started on every request unless an existing long-running conversation is being resumed. Even if your application does not explicitly specify conversation handling a conversation will be initialized for the request. A temporary conversation survives a redi |
| Long-running Conversations | A temporary conversation is promoted to longrunning if you tell Seam to begin a long-running conversation. Promoting a conversation to long-running informs Seam to maintain the conversation between requests. The conversation is demoted to temporary if you tell Seam to end a long-running conversation. |
Conversation Management Annotations
These annotations provide declarative conversation management through Seam components.
| Annotation | Use | Description |
| @Conversational | Type, Method | A component or method annotated as @Conversational can only be accessed in the context of a long-running conversation. |
| @Begin | Method | Marks a method as beginning a long-running conversation. The long-running conversation will only end upon method return if: the method is void return-type or the method returns a non-null outcome. |
| @End | Method | Marks a method as ending a long-running conversation. The long-running conversation will only begin upon method return if: the method is void return-type or the method returns a non-null outcome. |
Conversation Management Usage
Some example usage patterns for conversation propagation.
| 1. Begin a conversation when the selectHotel method is invoked: |
|
| 2. End a conversation when the booking is confirmed: |
|
| Note the use of the beforeRedirect parameter. Recall that a conversation is really only demoted to temporary when ended and survives a redirect. Here the conversation is destroyed before the redirect. |
| 3. Begin a conversation with manual flushing enabled: |
|
| This ensures that the booking would not be persisted until an EntityManager.flush() is invoked manually. This is only usable with an SMPC and Hibernate as the persistence provider. |
| 4. Begin or join the conversation when the hotel page is accessed: |
|
| This example demonstrates conversation management through the pages.xml file. The pages.xml file provides a navigation-centric approach to conversation management directly relating the boundaries of a conversation to page navigation. |
| 5. Leave the scope of an existing conversation to return to the main page: |
|
| Use of the <s:link> and <s:button> tags in your view are common to either propagate a conversation across a GET request or to leave the scope of an existing conversation. |
Seam Distribution Conversation Management Examples
The following examples are distributed with Seam and provide great resources for configuring your application.
| Example | Directory | Description |
| Seam Booking | examples/booking | Demonstrates the most basic conversation management through use of annotations. |
| Nested Booking | examples/nestedbooking | Demonstrates the use of nested conversations through annotations. |
| Seam Space | examples/seamspace | Demonstrates conversation management through pages.xml as well as use of natural conversations. |

It is a common misconception that conversations should always be ended when navigating elsewhere in an application. Seam ensures that these abandoned, or background conversations are cleaned up after a period of time (the conversation-timeout setting). The conversation that the user last interacted, the foreground conversation, will only timeout when the session times out. See the Core Namespace to learn how to configure the conversation-timeout setting.
Common Application Configuration
The Core Namespace
Schema URI
http://jboss.com/products/seam/core
Schema XSD
http://jboss.com/products/seam/core-2.1.xsd
The core namespace includes support for configuration of Seam components found in org.jboss.seam.core. This includes the JNDI pattern used to lookup EJB components, debug mode settings, conversation management, inclusion of custom resource bundles, and POJO cache settings.
Core Namespace Diagram

Core Namespace Elements
| Element | Description |
| <core:init> | Initialization parameters including debug settings and configuration of the jndiPattern for EJB users. |
| <core:resource-loader> | Allows configuration of custom resource bundle-names for loading messages. |
| <core:bundle-names> | Custom bundle names can be specified which are searched depth-first for messages. This overrides the standard messages.properties. |
| <core:manager> | Configures conversation management settings such as timeouts, parameter names, uri-encoding, and the default-flush-mode. |
| <core:interceptors> | Configures the list of interceptors that should be enabled for all components. All built-in interceptors must be specified with any additional interceptors. |
| Core Namespace Example |
|
The following example demonstrates use of the core namespace:
|
| The above configuration tells Seam how to find EJB components in the JNDI registry and whether to operate in debug mode allowing features such as incremental deployment. The manager configuration ensures that background conversations timeout after 10 minutes through the conversation-timeout setting. Note the setting is configured in milliseconds. The cid parameter simply specifies how our conversation ID should be represented in a query string, e.g. /book.seam?cid=20. |
Note the use of the default-flush-mode setting. If you are using a Seam-managed Persistence Context (SMPC), which will be discussed shortly, this setting will save constant repetition of the flush-mode setting when beginning conversations.

It is generally a good idea to keep some application configuration in properties files. This makes it simple for administrators to easily tweak deployment- specific settings (e.g. database settings).
Seam lets you place wildcards of the form @propertyName@ in your components.xml file. Seam uses the components.properties file in the classpath to replace the properties by name. Seam-gen projects use this approach by default to dynamically replace the jndiPattern and debug settings.
The Transaction Namespace
Transaction Namespace URI
http://jboss.com/products/seam/transaction
Transaction Namespace XSD
http://jboss.com/products/seam/transaction-2.1.xsd
Transactions are an essential feature for database-driven web applications. In each conversation, we typically need to update multiple database tables. If an error occurs in the database operation (e.g. a database server crashes), the application needs to inform the user, and all the updates this conversation has written into the database must be rolled back to avoid partially updated records. In other words, all database updates in the conversation must happen inside an atomic operation. Seam-managed transactions along with Seam-managed persistence enables you to do just that.
Transaction Namespace Diagram

| Element | Description |
| <transaction:ejb-transaction> | Configures the EJB transaction synchronization component which should be installed if you are working in a Java EE 5 environment. |
| <transaction:entity-transaction> | Configures JPA RESOURCE_LOCAL transaction management where the the managedpersistence-context is injected as an Expression Language (EL) attribute. This attribute is not required if your EntityManager is named entityManager. |
| <transaction:hibernate-transaction> | Configures Hibernate managed transactions where the persistence:managed-hibernatesession is injected as an Expression Language (EL) attribute. This attribute is not required if your Session is named session. |
| <transaction:no-transaction> | Disables Seam-managed transactions. |
| Transaction Namespace Example |
|
The following example configures the EJB transaction
|
Note that this indicates the application is being deployed to a JEE 5 environment.
The Persistence Namespace
Persistence Namespace URI
http://jboss.com/products/seam/persistence
Persistence Namespace XSD
http://jboss.com/products/seam/persistence-2.1.xsd
When JPA is used within an EJB environment, an extended persistence context can be associated with a stateful session bean. An extended persistence context lives between requests and is scoped to the stateful component allowing entities to remain managed. The EJB3 approach has several shortcomings:
- What if my application does not operate in an EJB environment?
- It can be tricky to ensure that the persistence context is shared between loosely coupled components.
- EJB3 does not include the concept of manual flushing.
A Seam-managed persistence context (or SMPC) is available for use in both environments and alleviates these issues altogether. An SMPC is just a built-in Seam component that manages an instance of EntityManager or Hibernate Session in the conversation context. You can inject it with @In.
Note that many of the options for configuring a HibernateSessionFactory have been omitted due to space constraints. For more options on configuring your HibernateSessionFactory, see the Seam Reference Documentation (http://seamframework.org/Documentation).
Persistence Namespace Diagram

Persistence Namespace Elements
| Element | Description |
| <persistence:entity-manager-factory> | Informs Seam to bootstrap a JPA EntityManagerFactory from your persistence.xml file. |
| <persistence:managed-persistence-context> | Configures a Seam managed JPA EntityManager to be available via injection. |
| <persistence-unit-jndi-name> | Allows the persistence unit’s JNDI name to be embedded as an element rather than an attribute. |
| <persistence:hibernate-session-factory> | If you choose to use Hibernate directly, informs Seam to bootstrap a HibernateSessionFactory. Allows your Hibernate configuration to be specified through a variety of approaches with the sub-elements shown in the namespace diagram. |
| <persistence:managed-hibernate-session> | Configures a Seam-managed Hibernate Session to be available via injection. |
| <persistence:filters> | Defines a set of Hibernate filters. Can only be used with Hibernate. |
| <persistence:filter> | Defines a Hibernate filter that is enabled whenever an EntityManager or Hibernate Session is first created. Can only be used with Hibernate. |
| <persistence:name> | Provides the name of the Hibernate filter. |
| <persistence:parameters> | Specifies key-value pairs setting the parameter values as Expression Language (EL) expressions for the Hibernate filter. |
| Persistence Namespace Example |
|
The following example demonstrates use of the persistence namespace:
|
|
As configured above, a Seam-managed EntityManager can be injected as:
The EntityManagerFactory is looked up by the configured JNDI name so this name must be consistent with your persistence.xml configuration. If you are using JBoss this can be configured with the following in the properties of your persistence-unit definition:
|
Seam Distribution Persistence Configuration Examples
The following examples are distributed with Seam and provide great resources for configuring your application.
| Example | Directory | Description |
| Booking | examples/booking | Demonstrates configuration of using a basic EJB PersistenceContext managed by the EJB container. |
| Hibernate Booking | examples/hibernate | Demonstrates configuration of using direct Hibernate persistence with a Seam-managed Hibernate Session. |
| JPA Booking | examples/jpa | Demonstrates use of an SMPC with JPA RESOURCE_LOCAL transaction management usable in non-EJB containers like Tomcat. |
Seam Security
Security is arguably one of the most important aspects of application development. Unfortunately due to its complexity security is often an afterthought which can lead to gaping holes in an application for malicious users to take advantage of. Fortunately, when using Seam this complexity is hidden making it simple to ensure that your next application is secure.
Seam security provides extensive configuration options making it useful in a wide array of implementations but also making it worthy of its own reference card. The basics of Seam security will be covered here which will address most use-cases and will allow you to get up-and-running quickly.
The Security Namespace
Security Namespace URI
http://jboss.com/products/seam/security
Security Namespace XSD
http://jboss.com/products/seam/security-2.1.xsd
The security namespace provides the hooks necessary to customize Seam security to fit your application needs whether you intend to use LDAP, a relational database, or any other custom authentication/authorization scheme.
Security Namespace Elements

Security Namespace Diagram
| Element | Description |
| <security:identity> | Configures the application-specific authentication implementation for the Seam Identity component. The IdentityManager is used for authentication by default. |
| <security:identity-manager> | Configures the management of a Seam application’s users and roles for a type of identity store (database, LDAP, etc). The JpaIdentityStore is the default. |
| <security:ldap-identity-store> | Declares an identity store that allows users and roles to be stored inside an LDAP directory. |
| <security:jpa-identity-store> | Declares an identity store that allows users and roles to be stored inside a relational database. |
| <security:permission-manager> | Configures a PermissionManager instance for management of persistent permissions which requires a PermissionStore instance. |
| <security:persistent-permission-resolver> | Allows configuration of a custom permission store. A permission store can be implemented by implementing the PermissionStore interface. |
| <security:rule-based-permission-resolver> | Allows the Drools rule base name to be specified when rule-based permissions are in use. |
| <security:jpa-permission-store> | PermissionStore implementation allowing user and role permissions to be stored and retrieved as JPA entities. |
| Security Namespace Example |
|
The JpaIdentityStore component provided by Seam 2.1 makes it simple to store users and roles inside a relational database.
|
| Above we need not configure the IdentityManager as the JpaIdentityStore is assumed by default. |
Securing your Application
Seam makes it easy to declare access constraints on web pages, UI components, and Java methods via tags, annotations, and JSF Expression Language (EL) expressions. Through this declarative approach Seam provides you with the ability to easily achieve a layered approach to security.
Security Annotations
| Annotation | Use | Description |
| @Restrict | Type, Method | Allows a component to be secured either at the method or the class level through evaluation of an Expression Language (EL) expression. |
| @Read | Method, Parameter | Declares a type-safe permission check to determine whether the current user has read permission for the specified class. |
| @Update | Method, Parameter | Declares a type-safe permission check to determine whether the current user has update permission for the specified class. |
| @Insert | Method, Parameter | Declares a type-safe permission check to determine whether the current user has insert permission for the specified class. |
| @Delete | Method, Parameter | Declares a type-safe permission check to determine whether the current user has delete permission for the specified class. |
| @PermissionCheck | Annotation | Declares a custom security annotation for performing type-safe permission checks where the required permission is the lowercase representation of the annotation name. |
| @RoleCheck | Annotation | Declares a custom security annotation for performing type-safe role checks where the required role is the lower-case representation of the annotation name. |
Security Expression Language (EL) Functions
These functions provide convenience for invoking role or permission checks through Expression Language (EL). This can be useful in your Facelets pages, in pages.xml, or in using the @Restrict annotation to provide security restrictions.
| Function | Description |
| #{s:hasRole(roleName)} | Expression Language (EL) function that invokes the hasRole method on the Identity component. Returns true if the current user has the specified role. |
| #{s:hasPermission(target, action)} | Expression Language (EL) function that invokes the hasPermission method on the Identity component. Delegates the call to the configured PermissionResolver. |
Seam Distribution Security Examples
The following examples are distributed with Seam and provide great resources for configuring your application.
| Example | Directory | Description |
| Seam Booking | examples/booking | Demonstrates the most basic authentication through use of an authenticate-method. |
| Seam Space | examples/seamspace | Demonstrates use of rule-based-permission-resolver, jpa-identity-store, and jpa-permission-store. |
APPLICATION FRAMEWORK
The Seam CRUD application framework essentially provides prepackaged Data Access Objects (DAOs). DAOs are highly repetitive as the DAOs for each entity class are largely the same. They are ideal for code reuse. Seam provides an application framework with built-in generic DAO components. You can develop simple CRUD web applications in Seam without writing a single line of Java "business logic" code.
The Framework Namespace
Framework Namespace URI
http://jboss.com/products/seam/framework
Framework Namespace XSD
http://jboss.com/products/seam/framework-2.1.xsd
The framework namespace configures components found in the org.jboss.seam.framework package.
Framework Namespace Diagram

Framework Namespace Elements
| Element | Description |
| <framework:entity-query> | Configures an EntityQuery controller instance for executing JPA queries. |
| <framework:entity-home> | Configures an EntityHome controller instance for managing JPA entities. |
| <framework:hibernate-entity-query> | Configures a HibernateQuery controller instance for executing Hibernate queries. |
| <framework:hibernate-entity-home> | Configures a HibernateEntityHome controller instance for managing Hibernate entities. |
| <framework:new-instance> | Declares the new instance managed by a home controller. |
| <framework:ejbql> | Declares the new instance managed by a home controller. |
| <framework:order> | Defines the order-by property for a Query instance. |
| <framework:restrictions> | Defines the where clause of a Query instance. |
| <framework:group-by> | Defines the group-by clause for a Query instance. |
| <framework:created-message> | A status message added when a Home controller creates a new entity instance. |
| <framework:updated-message> | A status message added when the Home controller updates an entity instance. |
| <framework:deleted-message> | A status message added when the Home controller deletes an entity instance. |
| Framework Namespace Example |
|
In the booking example we could use an EntityHome instance to manage retrieval of the Hotel entity. The configuration below achieves this:
|
| When a hotel is requested for injection or through Expression Language (EL) the hotelHome will be invoked to retrieve the hotel based on the current hotelId. This of course requires that the requested hotelId be made available in the current context. This can easily be achieved through use of a request parameter or outjection. |
Seam Distribution Framework Examples
The following examples are distributed with Seam and provide great resources for configuring your application.
| Example | Directory | Description |
| Seam Pay | examples/seampay | Demonstrates use of entity-query and entityhome elements. |
| DVD Store | examples/dvdstore | Demonstrates use of entity-query and entityhome elements. |
| Contact List | examples/contactlist | Demonstrates use of entity-query and entityhome with embedded namespace elements. Also demonstrates use of restrictions. |




