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:
Stateless context
Event (or request) context
Page context
Conversation context
Session context
Business process context
Application context
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.
Components which are truly stateless (stateless session beans, primarily) always live in the stateless context (this is really a non-context). Stateless components are not very interesting, and are arguably not very object-oriented. Nevertheless, they are important and often useful.
The event context is the "narrowest" stateful context, and is a generalization of the notion of the web request context to cover other kinds of events. Nevertheless, the event context associated with the lifecycle of a JSF request is the most important example of an event context, and the one you will work with most often. Components associated with the event context are destroyed at the end of the request, but their state is available and well-defined for at least the lifecycle of the request.
When you invoke a Seam component via RMI, or Seam Remoting, the event context is created and distroyed just for the invocation.
The page context allows you to associate state with a particular instance of a rendered page. You can initialize state in your event listener, or while actually rendering the page, and then have access to it from any event that originates from that page. This is especially useful for functionality like clickable lists, where the list is backed by changing data on the server side. The state is actually serialized to the client, so this construct is extremely robust with respect to multi-window operation and the back button.
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", 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.
Alternatively, Seam may be configured to keep conversational state in the client browser.
A session context holds state associated with the user login session. While there are some cases where it is useful to share state between several conversations, we generally frown on the use of session context for holding components other than global information about the logged in user.
In a JSR-168 portal environment, the session context represents the portlet session.
The business process context holds state associated with the long running business process. This state is managed and made persistent by the BPM engine (JBoss jBPM). The business process spans multiple interactions with multiple users, so this state is shared between multiple users, but in a well-defined manner. The current task determines the current business process instance, and the lifecycle of the business process is defined externally using a process definition language, so there are no special annotations for business process demarcation.
The application context is the familiar servlet context from the servlet spec. Application context is mainly useful for holding static information such as configuration data, reference data or metamodels. For example, Seam stores its own configuration and metamodel in the application context.
A context defines a namespace, a set of context variables. These work much the same as session or request attributes in the servlet spec. You may bind any value you like to a context variable, but usually we bind Seam component instances to context variables.
So, within a context, a component instance is identified by the context variable name (this is usually, but not always, the same as the component name). You may programatically access a named component instance in a particular scope via the Contexts class, which provides access to several thread-bound instances of the Context interface:
User user = (User) Contexts.getSessionContext().get("user");
You may also set or change the value associated with a name:
Contexts.getSessionContext().set("user", user);
Usually, however, we obtain components from a context via injection, and put component instances into a context via outjection.
Sometimes, as above, component instances are obtained from a particular known scope. Other times, all stateful scopes are searched, in priority order. The order is as follows:
Event context
Page context
Conversation context
Session context
Business process context
Application context
You can perform a priority search by calling Contexts.lookupInStatefulContexts(). Whenever you access a component by name from a JSF page, a priority search occurs.
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.
EJB 3.0 stateless session beans
EJB 3.0 stateful session beans
EJB 3.0 entity beans
JavaBeans
EJB 3.0 message-driven beans
Stateless session bean components are not able to hold state across multiple invocations. Therefore, they usually work by operating upon the state of other components in the various Seam contexts. They may be used as JSF action listeners, but cannot provide properties to JSF components for display.
Stateless session beans always live in the stateless context.
Stateless session beans are the least interesting kind of Seam component.
Stateful session bean components are able to hold state not only across multiple invocations of the bean, but also across multiple requests. Application state that does not belong in the database should usually be held by stateful session beans. This is a major difference between Seam and many other web application frameworks. Instead of sticking information about the current conversation directly in the HttpSession, you should keep it in instance variables of a stateful session bean that is bound to the conversation context. This allows Seam to manage the lifecycle of this state for you, and ensure that there are no collisions between state relating to different concurrent conversations.
Stateful session beans are often used as JSF action listener, and as backing beans that provide properties to JSF components for display or form submission.
By default, stateful session beans are bound to the conversation context. They may never be bound to the page or stateless contexts.
Entity beans may be bound to a context variable and function as a seam component. Because entities have a persistent identity in addition to their contextual identity, entity instances are usually bound explicitly in Java code, rather than being instantiated implicitly by Seam.
Entity bean components do not support bijection or context demarcation. Nor does invocation of an entity bean trigger validation.
Entity beans are not usually used as JSF action listeners, but do often function as backing beans that provide properties to JSF components for display or form submission. In particular, it is common to use an entity as a backing bean, together with a stateless session bean action listener to implement create/update/delete type functionality.
By default, entity beans are bound to the conversation context. They may never be bound to the stateless context.
Javabeans may be used just like a stateless or stateful session bean. However, they do not provide the functionality of a session bean (declarative transaction demarcation, declarative security, automatic clustered state replication, EJB 3.0 persistence, timeout methods, etc).
In a later chapter, we show you how to use Seam and Hibernate without an EJB container. In this use case, components are JavaBeans instead of session beans.
By default, JavaBeans are bound to the conversation context.
Message-driven beans may function as a seam component. However, message-driven beans are called quite differently to other Seam components - instead of invoking them via the context variable, they listen for messages sent to a JMS queue or topic.
Message-driven beans may not be bound to a Seam context. Nor do they have access to any Seam contexts apart from the EVENT and APPLICATION contexts. However, they do support bijection and some other Seam functionality.
In order to perform its magic (bijection, context demarcation, validation, etc), Seam must intercept component invocations. For JavaBeans, Seam is in full control of instantiation of the component, and no special configuration is needed. For entity beans, interception is not required since bijection and context demarcation are not defined. For session beans, we must register an EJB interceptor for the session bean component. We could use an annotation, as follows:
@Stateless @Interceptors(SeamInterceptor.class) public class LoginAction implements Login { ... }
But a much better way is to define the interceptor in ejb-jar.xml.
Almost all seam components need a name. We 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.
Just like in JSF, a seam component instance is usually bound to a context variable with the same name as the component name. So, for example, we would access the LoginAction using Contexts.getStatelessContext().get("loginAction"). In particular, whenever Seam itself instantiates a component, it binds the new instance to a variable with the component name. However, again like JSF, it is possible for the application to bind a component to some other context variable by programmatic API call. This is only 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.
For very large applications, and for built-in seam components, qualified names are often used.
@Name("com.jboss.myapp.loginAction") @Stateless @Interceptors(SeamInterceptor.class) public class LoginAction implements Login { ... }
Unfortunately, JSF's expression language interprets a period as a property dereference. So, inside a JSF expression, we use $ to indicate a qualified component name:
<h:commandButton type="submit" value="Login" action="#{com$jboss$myapp$loginAction.login}"/>
We can override the default scope (context) of a component using the @Scope annotation. This lets us define what context a component instance is bound to, when it is instantiated by Seam.
@Name("user") @Entity @Scope(SESSION) public class User { ... }
org.jboss.seam.ScopeType defines an enumeration of possible scopes.
Some Seam component classes can fulfill more than one role in the system. For example, we often have a User class which is usually used as a session-scoped component representing the current user but is used in user administration screens as a conversation-scoped component. The @Role annotation lets us define an additional named role for a component, with a different scope—it lets us bind the same component class to different context variables. (Any Seam component instance may be bound to multiple context variables, but this lets us do it at the class level, and take advantage of auto-instantiation.)
@Name("user") @Entity @Scope(CONVERSATION) @Role(name="currentUser", scope=SESSION) public class User { ... }
The @Roles annotation lets us specify as many additional roles as we like.
@Name("user") @Entity @Scope(CONVERSATION) @Roles({@Role(name="currentUser", scope=SESSION) @Role(name="tempUser", scope=EVENT)}) public class User { ... }
Like many good frameworks, Seam eats its own dogfood and is implemented mostly as a set of built-in Seam interceptors (see later) and Seam components. This makes it easy for applications to interact with built-in components at runtime or even customize the basic functionality of Seam by replacing the built-in components with custom implementations. The built-in components are defined in the Seam namespace org.jboss.seam.core and the Java package of the same name.
The built-in components may be injected, just like any Seam components, but they also provide convenient static instance() methods:
FacesMessages.instance().add("Welcome back, #{user.name}!");
Seam was designed to integrate tightly in a Java EE 5 environment. However, we understand that there are many projects which are not running in a full EE environment. We also realize the critical importance of easy unit and integration testing using frameworks such as TestNG and JUnit. So, we've made it easy to run Seam in Java SE environments by allowing you to boostrap certain critical infrastructure normally only found in EE environments by installing built-in Seam components.
For example, you can run your EJB3 components in Tomcat or an integration test suite just by installing the built-in component org.jboss.seam.core.ejb, which automatically bootstraps the JBoss Embeddable EJB3 container and deploys your EJB components.
Or, if you're not quite ready for the Brave New World of EJB 3.0, you can write a Seam application that uses only JavaBean components, together with Hibernate3 for persistence, by installing the built-in component org.jboss.seam.core.hibernate. When using Hibernate outside of a J2EE environment, you will also probably need a JTA transaction manager and JNDI server, which are available via the built-in component org.jboss.seam.core.microcontainer. This lets you use the bulletproof JTA/JCA pooling datasource from JBoss application server in an SE environment like Tomcat!
Seam provides two basic approaches to configuring components: configuration via property settings in a properties file or web.xml, and configuration via components.xml.
Seam components may be provided with configuration properties either via servlet context parameters, or via a properties file named seam.properties in the root of the classpath.
The configurable Seam component must expose a JavaBeans-style property setter methods for the configurable attributes. If a seam component named com.jboss.myapp.settings has a setter method named setLocale(), we can provide a property named com.jboss.myapp.settings.locale in the seam.properties file or as a servlet context parameter, and Seam will set the value of the locale attribute whenever it instantiates the component.
Note that it is not possible to configure stateless session beans or entity beans.
The same mechanism is used to configure Seam itself. For example, to set the conversation timeout, we provide a value for org.jboss.seam.core.manager.conversationTimeout in web.xml or seam.properties. (There is a built-in Seam component named org.jboss.seam.core.manager with a setter method named setConversationTimeout().)
The components.xml is a bit more powerful than property settings. It lets you:
Configure components that have been installed automatically—including both built-in components, and application components that have been annotated with the @Name annotation and picked up by Seam's deployment scanner.
Install classes with no @Name annotation as Seam components—this is most useful for certain kinds of infrastructural components which can be installed multiple times different names (for example Seam-managed persistence contexts).
Install components that do have a @Name annotation but are not installed by default (this is the case for certain built-in components).
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. The components.xml file lets us handle special cases where that is not the case.
For example, the following components.xml file installs the JBoss Embeddable EJB3 container:
<components> <component class="org.jboss.seam.core.Ejb"/> </components>
This one installs and configures two different Seam-managed persistence contexts:
<components> <component name="customerDatabase" class="org.jboss.seam.core.ManagedPersistenceContext"> <property name="persistenceUnitJndiName">java:/customerEntityManagerFactory</property> </component> <component name="accountingDatabase" class="org.jboss.seam.core.ManagedPersistenceContext"> <property name="persistenceUnitJndiName">java:/accountingEntityManagerFactory</property> </component> </components>
Sometimes we want to reuse the same components.xml file with minor changes during both deployment and testing. Seam let's 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.
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:
contextual - bijection is used to assemble stateful components from various different contexts (a component from a "wider" context may even have a reference to a component from a "narrower" context)
bidirectional - values are injected from context variables into attributes of the component being invoked, and also outjected from the component attributes back out to the context, allowing the component being invoked to manipulate the values of contextual variables simply by setting its own instance variables
dynamic - since the value of contextual variables changes over time, and since Seam components are stateful, bijection takes place every time a component is invoked
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 @Interceptors(SeamInterceptor.class) public class LoginAction implements Login { @In User user; ... }
or into a setter method:
@Name("loginAction") @Stateless @Interceptors(SeamInterceptor.class) 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).
You can even inject the value of an expression:
@Name("loginAction") @Stateless @Interceptors(SeamInterceptor.class) public class LoginAction implements Login { @In("#{user.username}") String username; ... }
(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 @Interceptors(SeamInterceptor.class) public class LoginAction implements Login { @Out User user; ... }
or from a getter method:
@Name("loginAction") @Stateless @Interceptors(SeamInterceptor.class) public class LoginAction implements Login { User user; @Out public User getUser() { return user; } ... }
An attribute may be both injected and outjected:
@Name("loginAction") @Stateless @Interceptors(SeamInterceptor.class) public class LoginAction implements Login { @In @Out User user; ... }
or:
@Name("loginAction") @Stateless @Interceptors(SeamInterceptor.class) public class LoginAction implements Login { User user; @In public void setUser(User user) { this.user=user; } @Out public User getUser() { return user; } ... }
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 built on top of Apache commons-logging 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); }
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); }
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. 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 @Within and @Around annotations to your interceptor classes to specify a partial order of interceptors.
@Around({BijectionInterceptor.class, ValidationInterceptor.class, ConversationInterceptor.class}) @Within(RemoveInterceptor.class) public class LoggedInInterceptor { ... }
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!
The Seam component model was developed for use with event-driven applications, specifically to enable the development of fine-grained, loosely-coupled components in a fine-grained eventing model. Events in Seam come in several types, most of which we have already seen:
JSF events
jBPM transition events
Seam page actions
Seam component-driven events
All of these various kinds of events are mapped to Seam components via JSF EL method binding expressions. For a JSF event, this is defined in the JSF template:
<h:commandButton value="Click me!" action="#{helloWorld.sayHello}"/>
For a jBPM transition event, it is specified in the jBPM process definition or pageflow definition:
<start-page name="hello" view-id="/hello.jsp"> <transition to="hello"> <action expression="#{helloWorld.sayHello}"/> </transition> </start-page>
You can find out more information about JSF events and jBPM events elsewhere. Lets concentrate for now upon the two additional kinds of events defined by Seam.
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.jsp" action="#{helloWorld.sayHello}"/> <pages>
Or we can use a wildcard to specify an action that applies to all view ids that match the pattern:
<pages> <page view-id="/hello/*" action="#{helloWorld.sayHello}"/> <pages>
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 delegate to the defined JSF navigation rules and a different view may end up being rendered.
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. For example:
TODO: translate struts action into page action
This is quite useful if you want to do complex things in response to non-faces requests (for example, HTTP GET requests).
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 WEB-INF/events.xml.
<events> <event type="hello"> <action expression="#{helloListener.sayHelloBack}"/> <action expression="#{logger.logHello}"/> </event> <events>
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 events.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"); } }
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!"); } }
If you don't like the events.xml file, we 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. All state is held in the Seam contexts, and is shared between components.