JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

How to develop applications using JBoss Seam?

September 17, 2009 by Krishna Srinivasan Leave a Comment

Seam 2.x Web DevelopmentThis book provides a complete walk-through of developing Web applications using Seam, Facelets, and RichFaces, and explains how to deploy them to the JBoss Application Server.

This book introduces you to the fundamentals of Seam applications, describing topics such as Injection, Outjection, and Bijection. You will understand the Facelets framework, AJAX, database persistence, and advanced Seam concepts, through the many examples explained in the book.

A practical approach is taken throughout the book to describe the technologies and tools involved. You will add functionality to Seam applications after you learn how to use the Seam Generator RAD tools and how to customize and fully test application functionality.
Hints and tips on how to use Seam and the JBoss Application Server are provided along the way.

What This Book CoversChapter 1 provides an overview of the Seam Framework, and describes the benefits that we, as Java developers, will gain by using the framework. We learn that Seam is much more than a framework, and that it comes packed with support for numerous other features.

Chapter 2 teaches you how to develop applications using Seam, and explains some of the features discussed in previous chapter. In this chapter, we will learn the basic structure of a Seam application and learn more about Seam components. We will also see exactly
how Seam bridges the gap between the Web tier and the Server tier.

Chapter 3 takes you through page navigation using Seam page flows. We also see how we can define page flow within the pages.xml file of our applications by defining both static rules and rules encompassing JSF expression language.

Chapter 4 shows you why Facelets is recommended, and what it offers over JSP. We’ll also look at the SeamGen tool and see why this is a much better way of creating Seam applications and building scripts. Finally, we bring both SeamGen and Facelets together and re-create the Vacation Planner project that we wrote in Chapter 3, (realizing in the course of doing so how much easier and more advanced it is), using these technologies

In Chapter 5, we take a look at TestNG and see how it can be used to build sets of test suites. We have a look at how Seam provides excellent facilities by allowing us to perform testing of our applications, at the class, Seam component, and user interface levels.

In Chapter 6, we take a look at RichFaces and learn that it’s a JSF component library that allows us to easily build rich user interfaces within web applications. This chapter explains how Seam is fully integrated with RichFaces, and that applications generated by
SeamGen require no special configuration to allow RichFaces to be used. This chapter also lists all of the components available within RichFaces.

Chapter 7 introduces database persistence with Seam. We take a closer look at how SeamGen helps us to create and configure our applications, allowing test, development, and production profiles to be configured.

Chapter 8 takes a closer look at what exactly a conversational application is and why they make web application development easier and more functional. We also take a look at different component scopes and see why they are important to Seam.

In Chapter 9, we take a look at AJAX and how it can be applied to Seam applications. We also take a closer look at the two different AJAX technologies within the Seam framework: Seam Remoting and AJAX4JSF.

Chapter 10 discusses how security is implemented within a Seam application highlighting the most common features, such as logon pages, user access rights, CAPTCHAs, and so on, which are used to secure Seam applications. We also highlight some of the more advanced security features that can be used.

Chapter 11 walks through some of the more advanced features of Seam, such as internationalization, URL rewriting, PDF document generation, and so on, and also discusses how these can be used within our web applications.

Developing Seam Applications

In the previous chapter, we learned what the Seam Framework is, and what it offers to Java developers. In this chapter, we are going to start learning how to develop applications using Seam, and we will see some of the features we had discussed previously. In this chapter, we will learn the basic structure of a Seam application. We will see in practice how Seam Injection and Outjection work, and we will learn more about Seam components. We will also see exactly how Seam bridges the gap between the Web tier (using Java Server Faces) and the Server tier (using Enterprise Java Beans).

Seam application architecture

As most enterprise Java developers are probably familiar with JSF and JSP, we will be using this as the view technology for our sample applications, until we have a solid understanding of Seam. In Chapter 4, we will introduce Facelets as the recommended view technology for Seam-based applications.

In a standard Java EE application, Enterprise Application Resource (EAR) files contain one or more Web Application Resource (WAR) files and one or more sets of Java Archive (JAR) files containing Enterprise JavaBeans (EJB) functionality.
Seam applications are generally deployed in exactly the same manner as depicted in the following diagram. It is possible to deploy Seam onto a servlet-only container (for example, Tomcat) and use POJOs as the server-side Seam components. However, in this situation, we don’t get any of the benefits that EJBs provide, such as security, transaction handling, management, or pooling.

seam-1

Seam components

Within Seam, components are simple POJOs. There is no need to implement any interfaces or derive classes from a Seam-specific base class to make Seam components classes. For example, a Seam component could be:

  • A simple POJO
  • a stateless Session Bean
  • a stateful Session Bean
  • a JPA entity and so on

Seam components are defined by adding the @Name annotation to a class definition. The @Name annotation takes a single parameter to define the name of the Seam component. The following example shows how a stateless Session Bean is defined as a Seam component called calcAction.

[code lang=”java”] package com.davidsalter.seamcalculator;
@Stateless
@Name(‘calcAction’)
public class CalcAction implements Calc {
…
}
[/code]

When a Seam application is deployed to JBoss, the log output at startup lists what Seam components are deployed, and what type they are. This can be useful for diagnostic purposes, to ensure that your components are deployed correctly. Output similar to the following will be shown in the JBoss console log when the CalcAction class is deployed:

[code] 21:24:24,097 INFO [Initialization] Installing components…
21:24:24,121 INFO [Component] Component: calcAction, scope:
STATELESS, type: STATELESS_SESSION_BEAN, class: com.davidsalter.
seamcalculator.CalcAction, JNDI: SeamCalculator/CalcAction/local
[/code]

Object Injection and Outjection

One of the benefits of using Seam is that it acts as the “glue” between the web technology and the server-side technology. By this we mean that the Seam Framework allows us to use enterprise beans (for example, Session Beans) directly within the Web tier without having to use Data Transfer Object (DTO) patterns and without worrying about exposing server-side functionality on the client.

Additionally, if we are using Session Beans for our server-side functionality, we don’t really have to develop an additional layer of JSF backing beans, which are essentially acting as another layer between our web page and our application logic.

In order to fully understand the benefits of Seam, we need to first describe what we mean by Injection and Outjection.

Injection is the process of the framework setting component values before an object is created. With injection, the framework is responsible for setting components (or injecting them) within other components. Typically, Injection can be used to allow component values to be passed from the web page into Seam components.

Outjection works in the opposite direction to Injection. With Outjection, components are responsible for setting component values back into the framework. Typically, Outjection is used for setting component values back into the Seam Framework, and these values can then be referenced via JSF Expression Language (EL) within JSF pages. This means that Outjection is typically used to allow data values to be passed from Seam components into web pages.

Seam allows components to be injected into different Seam components by using the @In annotation and allows us to outject them by using the @Out annotation. For example, if we have some JSF code that allows us to enter details on a web form, we may use an tag such as this:

[code lang=”html”] <h:inputText value=’#{calculator.value1}’ required=’true’/>
[/code]

The Seam component calculator could then be injected into a Seam component using the @In annotation as follows:

[code lang=”java”] @In
private Calculator calculator;
[/code]

With Seam, all of the default values on annotations are the most likely ones to be used. In the preceding example therefore, Seam will look up a component called calculator and inject that into the calculator variable. If we wanted Seam to inject a variable with a different name to the variable that it is being injected into, we can adorn the @In annotation with the value parameter.

[code lang=”java”] @In (value=’myCalculator’)
private Calculator calculator;
[/code]

In this example, Seam will look up a component called myCalculator and inject it into the variable calculator.

Similarly, if we want to outject a variable from a Seam component into a JSF page, we would use the @Out annotation.

[code lang=”java”] @Out
private Calculator calculator;
[/code]

The outjected calculator object could then be used in a JSF page in the following manner:

[code lang=”html”] <h:outputText value=’#{calculator.answer}’/>
[/code]

Example application

To see these concepts in action, and to gain an understanding of how Seam components are used instead of JSF backing beans, let us look at a simple calculator web application. This simple application allows us to enter two numbers on a web page. Clicking the Add button on the web page will cause the sum of the numbers to be displayed.

This basic application will give us an understanding of the layout of a Seam application and how we can inject and outject components between the business layer and the view. The application functionality is shown in the following screenshot.

seam-2 

The sample code for this application can be downloaded from the Packt web site, at http://www.packtpub.com/support.

For this sample application, we have a single JSF page that is responsible for:

  • Reading two numeric values from the user
  • Invoking business logic to add the numbers together
  • Displaying the results of adding the numbers together

[code lang=”java”]
<%@ taglib uri=’http://java.sun.com/jsf/html’ prefix=’h’ %>
<%@ taglib uri=’http://java.sun.com/jsf/core’ prefix=’f’ %>
<html>
<head>
<title>Seam Calculator</title>
</head>
<body>
<f:view>
<h:form>
<h:panelGrid columns=’2′>
Value 1: <h:inputText value=’#{calculator.
value1}’ />
Value 2: <h:inputText value=’#{calculator.
value2}’ />
Add them together gives: <h:outputText value=’
#{calculator.answer} ‘/>
</h:panelGrid>
<h:commandButton value=’Add’ action=
‘#{calcAction.calculate}’/>
</h:form>
</f:view>
</body>
</html>
[/code]

We can see that there is nothing Seam-specific in this JSF page. However, we are binding two inputText areas, one outputText area, and a button action to Seam components by using standard JSF Expression Language.

seam-3Our business logic for this sample application is performed in a simple POJO class called Calculator.java.

[code lang=”java”]
package com.davidsalter.seamcalculator;

import java.io.Serializable;

import org.jboss.seam.annotations.Name;

@Name(‘calculator’)

public class Calculator {
private double value1;
private double value2;
private double answer;
public double getValue1() {
return value1;
}
public void setValue1(double value1) {
this.value1 = value1;
}
public double getValue2() {
return value2;
}
public void setValue2(double value2) {
this.value2 = value2;
}
public double getAnswer() {
return answer;
}
public void add() {
this.answer = value1 + value2;
}
}
[/code]

This class is decorated with the @Name(“calculator”) annotation, which causes it to be registered to Seam with the name, “calculator”. The @Name annotation causes this object to be registered as a Seam component that can subsequently be used within other Seam components via Injection or Outjection by using the @In and @Out annotations.

Finally, we need to have a class that is acting as a backing bean for the JSF page that allows us to invoke our business logic. In this example, we are using a Stateless Session Bean. The Session Bean and its local interface are as follows.

In the Java EE 5 specification, a Stateless Session Bean is used to represent a single application client’s communication with an application server. A Stateless Session Bean, as its name suggests, contains no state information; so they are typically used as transaction façades. A Façade is a popular design pattern, which defines how simplified access to a system can be provided. For more information about the Façade pattern, check out the following link:

[code]http://java.sun.com/blueprints/corej2eepatterns/Patterns/SessionFacade.html
[/code]

Defining a Stateless Session Bean using Java EE 5 technologies requires an interface and an implementation class to be defined. The interface defines all of the methods that are available to clients of the Session Bean, whereas the implementation class contains a concrete implementation of the interface. In Java EE 5, a Session Bean interface is annotated with either the @Local or @Remote or both annotations. An @Local interface is used when a Session Bean is to be accessed locally within the same JVM as its client (for example, a web page running within an application server). An @Remote interface is used when a Session Bean’s clients are remote to the application server that is running within a different JVM as the application server.

There are many books that cover Stateless Session Beans and EJB 3 in depth, such as EJB 3 Developer’s Guide by Michael Sikora, published by Packt Publishing. For more information on this book, check out the following link:

[code]http://www.packtpub.com/developer-guide-for-ejb3
[/code]

In the following code, we are registering our CalcAction class with Seam under the name calcAction. We are also Injecting and Outjecting the calculator variable so that we can use it both to retrieve values from our JSF form and pass them back to the form.

[code lang=”java”] package com.davidsalter.seamcalculator;
import javax.ejb.Stateless;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Name;

@Stateless
@Name(‘calcAction’)
public class CalcAction implements Calc {
@In
@Out
private Calculator calculator;
public String calculate() {
calculator.add();
return ”;
}
}
package com.davidsalter.seamcalculator;
import javax.ejb.Local;
@Local
public interface Calc {
public String calculate();
}
[/code]

That’s all the code we need to write for our sample application. If we review this code, we can see several key points where Seam has made our application development easier:

  • All of the code that we have developed has been written as POJOs, which will make unit testing a lot easier.
  • We haven’t extended or implemented any special Seam interfaces.
  • We’ve not had to define any JSF backing beans explicitly in XML.
  • We’re using Java EE Session Beans to manage all of the business logic and web-tier/business-tier integration.
  • We’ve not used any DTO objects to transfer data between the web and the business tiers. We’re using a Seam component that contains both state and behavior.

If you are familiar with JSF, you can probably see that adding Seam into a fairly standard JSF application has already made our development simpler.

Finally, to enable Seam to correctly find our Seam components and deploy them correctly to the application server, we need to create an empty file called seam. properties and place it within the root of the classpath of the EJB JAR file. Because this file is empty, we will not discuss it further here. We will, however, see the location of this file in the section Application layout, later in this chapter.

To deploy the application as a WAR file embedded inside an EAR file, we need to write some deployment descriptors.

WAR file deployment descriptors

To deploy a WAR file with Seam, we need to define several files within the \WEB-INF directory of the archive:

  • web.xml
  • faces-config.xml
  • components.xml

First let’s take a look at the web.xml file. This is a fairly standard file that specifies the SeamListener class, which aids internal Seam initialization and cleanup. This file also specifies that all pages with the extension .seam will be run as JSF pages.

[code lang=”xml”] <?xml version=’1.0′ ?>
<web-app xmlns=’http://java.sun.com/xml/ns/javaee’
xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance’
xsi:schemaLocation=’http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd’
version=’2.5′>
<listener>
<listener-class>org.jboss.seam.servlet.
SeamListener</listener-class>
</listener>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.jsp</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.seam</url-pattern>
</servlet-mapping>
</web-app>
[/code]

The faces-config.xml file allows Seam to be integrated into the JSF page life cycle, by adding the org.jboss.seam.jsf.SeamPhaseListener into the life cycle events chain.

[code lang=”xml”] <?xml version=’1.0′ encoding=’UTF-8′?>
<faces-config version=’1.2′
xmlns=’http://java.sun.com/xml/ns/javaee’
xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance’
xsi:schemaLocation=’http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd’>
<lifecycle>
<phase-listener>org.jboss.seam.jsf.
SeamPhaseListener</phase-listener>
</lifecycle>
</faces-config>
[/code]

Finally, the components.xml file allows any Seam components that we may be using to be configured. In our sample application, the only configuration that we are performing is specifying the JNDI pattern to allow EJB components to be looked up by Seam.

[code lang=”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:xsi=’http://www.w3.org/2001/XMLSchema-instance’
xsi:schemaLocation=’http://jboss.com/products/seam/core
http://jboss.com/products/seam/core-2.1.xsd
http://jboss.com/products/seam/components
http://jboss.com/products/seam/components-2.1.xsd’>
<core:init jndi-pattern=’@jndiPattern@’/>
</components>
[/code]

In the later chapters, we will look in detail at the components.xml file, as it is in this file that we will specify Seam-specific information such as security and web page viewing options.

EAR file deployment descriptors

To deploy an EAR file with Seam on JBoss, we need to define several deployment descriptors within the \META-INF directory of the archive:

  • application.xml
  • ejb-jar.xml
  • jboss-app.xml

The application.xml file allows us to define the modules that are to be deployed to JBoss. In this file, we need to specify the WAR file for our application and the JAR file that contains our Session Beans. We must also include a reference to the jboss-seam.jar file.

[code lang=”xml”] <?xml version=’1.0′ encoding=’UTF-8′?>
<application xmlns=’http://java.sun.com/xml/ns/javaee’
xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance’
xsi:schemaLocation=’http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/application_5.xsd’
version=’5′>
<display-name>SeamCalculator</display-name>
<module>
<web>
<web-uri>SeamCalculator.war</web-uri>
<context-root>/SeamCalculator</context-root>
</web>
</module>
<module>
<ejb>SeamCalculator.jar</ejb>
</module>
<module>
<ejb>jboss-seam.jar</ejb>
</module>
</application>
[/code]

In the ejb-jar.xml file, we must attach the org.jboss.seam.ejb.SeamInterceptor class onto all our EJBs.

[code lang=”xml”] <?xml version=’1.0′ encoding=’UTF-8′?>
<ejb-jar xmlns=’http://java.sun.com/xml/ns/javaee’
xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance’
xsi:schemaLocation=’http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd’
version=’3.0′>
<interceptors>
<interceptor>
<interceptor-class>org.jboss.seam.ejb.
SeamInterceptor</interceptor-class>
</interceptor>
</interceptors>
<assembly-descriptor>
<interceptor-binding>
<ejb-name>*</ejb-name>
<interceptor-class>org.jboss.seam.ejb.
SeamInterceptor</interceptor-class>
</interceptor-binding>
</assembly-descriptor>
</ejb-jar>
[/code]

Finally, we can specify a class loader for our Seam application in jboss-app.xml so that there are no confl icts between the classes deployed to the JBoss Application Server and the ones deployed to our application.

[code lang=”xml”] <?xml version=’1.0′ encoding=’UTF-8′?>
<!DOCTYPE jboss-app
PUBLIC ‘-//JBoss//DTD J2EE Application 5.0//EN’
‘http://www.jboss.org/j2ee/dtd/jboss-app_5_0.dtd’>
<jboss-app>
<loader-repository>
seam.jboss.org:loader=SeamCalculator
</loader-repository>
</jboss-app>
[/code]

Application layout

Before we deploy and run the test application, let’s take a look at the layout of our sample application. As you can see in the following screenshot, the layout of the application follows the standard layout of a Java EE application. The application is deployed as a single EAR file. Within the EAR file, we have the Seam JAR file, our EJB JAR file, and our web application EAR file. This is the standard layout that all of our Seam applications are going to follow.

seam-4

Testing the application

Now that we have looked at the code for both the application and the deployment descriptors, let’s build the application and test it before deploying it to the JBoss Application Server.

It is traditionally quite difficult to perform unit tests on enterprise applications because of their nature. Without using Seam, the testing of web pages and Java EE resources (for example, Session Beans) requires that the application be deployed to an application server. This makes testing more difficult and can vastly increase the development time of applications.

However, Seam offers great support for testing applications outside the application server, including support for testing web pages. The standard testing framework used with Seam is TestNG (http://www.testng.org). However, there are some Seam-specific extensions that make testing easier. We’ll cover the full testing of Seam applications in a later chapter, but for now, let’s see how to test the business logicof our application, and indeed any POJOs that we can write, by using a standard TestNG unit test.

TestNG uses Java 5 annotations to allow methods to be declared as tests. To declare a method as a unit test, we simply need to adorn the method with the @Test annotation. Within a test, we can then assert different conditions to test whether our code is working as expected.

We could write a simple test for our calculator application as follows:

[code lang=”java”] package com.davidsalter.seamcalculator.test;
import com.davidsalter.seamcalculator.Calculator;
import org.testng.annotations.Test;
public class CalculatorTest {
private static double tolerance = 0.001;
@Test
public void testAdd() throws Exception {
Calculator testCalculator = new Calculator();
testCalculator.setValue1(10.0);
testCalculator.setValue2(20.0);
testCalculator.add();
assert (testCalculator.getAnswer() – 30.0 &lt; tolerance);
}
}
[/code]

This test simply instantiates an instance of the Calculator class, sets up some test data, and invokes the add() method before asserting that the answer is as expected.

Before we can run this unit test, we must also define an XML file that details which tests to run. For Seam tests, this file is typically called AllTests. xml. The contents of this file, for our sample application, are as follows:

[code lang=”html”] <!DOCTYPE suite SYSTEM ‘http://testng.org/testng-1.0.dtd’ >
<suite name=’Calculator – All’ verbose=’1′>
<test name=’Calculator’>
<packages>
<package name=’com.davidsalter.seamcalculator.test’/>
</packages>
</test>
</suite>
[/code]

Finally, before we can build and test the application, we need to copy a few JAR files from the Seam installation into our build path. To build and test a basic Seam application, we need to build against some of the Seam JAR files:

  • jboss-seam.jar – This contains the main Seam Framework such as the @In and @Out annotations
  • ejb-api.jar – This contains the references we need to build EJB 3 Session Beans
  • testng.jar – This contains the TestNG framework that allows us to test our application

All of these JAR files can be found in the <jboss_seam>/lib directory, where <jboss_seam> is the directory that you have installed Seam into. If you have taken the sample application from the download bundle for this chapter, copy these files into the /lib directory of the project.

To test the sample application, we need to execute the Test target in the ant build file, as shown in the following screenshot.

seam-5Executing the tests should show that one test has been run, and that there were no failures and no skipped tests. Assuming that the test was completed successfully, we can be fairly confident that our application will run correctly when built and deployed to the application server.

Building and deploying the application

In the previous section, we saw how to perform a basic unit test to verify that the application logic is functioning correctly. Once all of our application’s unit tests succeed (one of them in this case), we can build the application and deploy it to JBoss.

To build and deploy the application, we use the ant script again. The ant script provides several different targets, allowing the project to be compiled, deployed, and archived into an EAR file. Executing the Info target provides the following help screen, which shows which targets are available.

seam-6 

seam-7 

Within the JBoss Application Server, applications can be hot deployed
by copying them into the <jboss_home>/server/default/deploy
directory. Similarly, to undeploy an application, just delete it from the
<jboss_home>/server/default/deploy directory.

To build and deploy the application to JBoss, execute the deploy task.

seam-8If the JBoss Application Server is running, we should see some log output appear on the JBoss console, ending with a line saying that the application has been deployed successfully, as shown below:

[code] [EARDeployer] Started J2EE application: file:/Applications/jboss-5.0.0.GA/server/default/deploy/SeamCalculator.ear

If we don’t see the application deployed to the JBoss Application Server
and there were no errors during compilation, check the value of the
jboss.home property within the build.properties file.
[/code]

Once we see the preceding line on the JBoss console, it means that JBoss has successfully deployed the application and we can test it out.

To run the application, visit the web site http://localhost:8080/SeamCalculator/calc.seam and try adding some numbers together to prove that the application is functioning as expected.

Seam data validation

So far we’ve looked at Seam and learned how Seam can act as JSF backing beans and how it can act as the glue between our server-tier Session Beans and our web-tier JSF pages. Unfortunately, though, users could easily break our sample application by entering invalid data (for example, entering blank values or non-numeric values into the edit boxes). Seam provides validation tools to help us to make our application more robust and provide feedback to our users. Let’s look at these tools now.

Data validation

In order to perform consistent data validation, we would ideally want to perform all data validation within our data model. We want to perform data validation in our data model so that we can then keep all of the validation code in one place, which should then make it easier to keep it up-to-date if we ever change our minds about allowable data values.

Seam makes extensive use of the Hibernate validation tools to perform validation of our domain model. The Hibernate validation tools grew from the Hibernate project (http://www.hibernate.org) to allow the validation of entities before they are persisted to the database. To use the Hibernate validation tools in an application, we need to add hibernate-validator.jar into the application’s class path, after which we can use annotations to define the validation that we want to use for our data model. We’ll discuss data validation and the Hibernate validator further in Chapter 7, when we talk about persisting objects to the database. But for now, let’s look at a few validations that we can add to our sample Seam Calculator application.

In order to implement data validation with Seam, we need to apply annotations either to the member variables in a class or to the getter of the member variables. It’s good practice to always apply these annotations to the same place in a class. Hence, throughout this book, we will always apply our annotation to the getter methods within classes.

In our sample application, we are allowing numeric values to be entered via edit boxes on a JSF form. To perform data validation against these inputs, there are a few annotations that can help us.

seam-9At this point, you may be wondering why we need to have an @Range validator, when by combining the @Min and @Max validators, we can get a similar effect. If you want a different error message to be displayed when a variable is set above its maximum value as compared to the error message that is displayed when it is set below its minimum value, then the @Min and @Max annotations should be used. If you are happy with the same error message being displayed when a variable is set outside its minimum or maximum values, then the @Range validator should be used. Effectively, the @Min and @Max validators are providing a finer level of error message
provision than the @Range validator.

The following code sample shows how these annotations can be applied to the sample application that we have written so far in this chapter, to add basic data validation to our user inputs.

[code lang=”java”] package com.davidsalter.seamcalculator;
import java.io.Serializable;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.faces.FacesMessages;
import org.hibernate.validator.Max;
import org.hibernate.validator.Min;
import org.hibernate.validator.Range;

@Name(‘calculator’)
public class Calculator implements Serializable {
private double value1;
private double value2;
private double answer;

@Min(value=0)
@Max(value=100)
public double getValue1() {
return value1;
}

public void setValue1(double value1) {
this.value1 = value1;
}

@Range(min=0, max=100)
public double getValue2() {
return value2;
}

public void setValue2(double value2) {
this.value2 = value2;
}

public double getAnswer() {
return answer;
}
…
}
[/code]

Displaying errors to the user

In the previous section, we saw how to add data validation to our source code to stop invalid data from being entered into our domain model. Now that we have reached a level of data validation, we need to provide feedback to the user to inform them of any invalid data that they have entered.

JSF applications have the concept of messages that can be displayed associated with different components. For example, if we have a form asking for a date of birth to be entered, we could display a message next to the entry edit box if an invalid date were entered. JSF maintains a collection of these error messages, and the simplest way of providing feedback to the user is to display a list of all of the error messages that were generated as a part of the previous operation.

In order to obtain error messages within the JSF page, we need to tell JSF which components we want to be validated against the domain model. This is achieved by using the or tags. These are Seam-specific tags and are not a part of the standard JSF runtime. In order to use these tags, we need to add the following taglib reference to the top of the JSF page.

[code lang=”java”]<%@ taglib uri=’http://jboss.com/products/seam/taglib’ prefix=’s’ %>[/code]

In order to use this tag library, we need to add a few additional JAR files into the WEB-INF/lib directory of our web application, namely:

  • jboss-el.jar
  • jboss-seam-ui.jar
  • jsf-api.jar
  • jsf-impl.jar

This tag library allows us to validate all of the components () within a block of JSF code, or individual components () within a JSF page.

To validate all components within a particular scope, wrap them all with the  tag as shown here:

[code lang=”html”] <h:form>
<s:validateAll>
<h:inputText value=’…’ />
<h:inputText value=’…’ />
</s:validateAll>
</h:form>
[/code]

To validate individual components, embed the tag within the component, as shown in the following code fragment.

[code lang=”html”] <h:form>
<h:inputText value=’…’ >
<s:validate/>
</h:inputText>
<h:inputText value=’…’ >
<s:validate/>
</h:inputText>
</h:form>
[/code]

After specifying that we wish validation to occur against a specified set of controls, we can display error messages to the user. JSF maintains a collection of errors on a page, which can be displayed in its entirety to a user via the tag.

seam-10It can sometimes be useful to show a list of all of the errors on a page, but it isn’t very useful to the user as it is impossible for them to say which error relates to which control on the form. Seam provides some additional support at this point to allow us to specify the formatting of a control to indicate error or warning messages to users.

Seam provides three different JSF facets () to allow HTML to be specified both before and after the offending input, along with a CSS style for the HTML. Within these facets, the tag can be used to output the message itself. This tag could be applied either before or after the input box, as per requirements.

seam-11aseam-12In order to specify these facets for a particular field, the tag must be specified outside the facet scope.

[code lang=”html”] <s:decorate>
<f:facet name=’aroundInvalidField’>
<s:span styleClass=’invalidInput’/>
</f:facet>
<f:facet name=’beforeInvalidField’>
<f:verbatim>**</f:verbatim>
</f:facet>
<f:facet name=’afterInvalidField’>
<s:message/>
</f:facet>
<h:inputText value=’#{calculator.value1}’ required=’true’ >
<s:validate/>
</h:inputText>
</s:decorate>
[/code]

In the preceding code snippet, we can see that a CSS style called invalidInput is being applied to any error or warning information that is to be displayed regarding the field. An erroneous input field is being adorned with a double asterisk (**) preceding the edit box, and the error message specific to the inputText field after is displayed in the edit box.

Applying these features to our sample application, the calc.jsp file will appear as follows:

[code lang=”html”] <%@ taglib uri=’http://java.sun.com/jsf/html’ prefix=’h’ %>
<%@ taglib uri=’http://java.sun.com/jsf/core’ prefix=’f’ %>
<%@ taglib uri=’http://jboss.com/products/seam/taglib’ prefix=’s’ %>

<html>
<head>
<title>Seam Calculator</title>
<link href=’styles.css’ rel=’stylesheet’ type=’text/css’ />
</head>
<body>
<f:view>
<h:form>
<h:panelGrid columns=’2′>
Value 1:
<s:decorate>
<f:facet name=’aroundInvalidField’>
<s:span styleClass=’invalidInput’/>
</f:facet>
<f:facet name=’beforeInvalidField’>
<f:verbatim>**</f:verbatim>
</f:facet>
<f:facet name=’afterInvalidField’>
<s:message/>
</f:facet>
<h:inputText value=’#{calculator.value1}’
required=’true’ >
<s:validate/>
</h:inputText>
</s:decorate>
Value 2:
<s:decorate>
<f:facet name=’aroundInvalidField’>
<s:span styleClass=’invalidInput’/>
</f:facet>
<f:facet name=’beforeInvalidField’>
<f:verbatim>**</f:verbatim>
</f:facet>
<f:facet name=’afterInvalidField’>
<s:message/>
</f:facet>
<h:inputText value=’#{calculator.value2}’
required=’true’>
<s:validate/>
</h:inputText>
</s:decorate>
Adding them together gives:
<h:outputText value=’#{calculator.answer}’/>
</h:panelGrid>
<h:commandButton value=’Add’
action=’#{calcAction.calculate}’/>
<h:messages/>
</h:form>
</f:view>
</body>
</html>
[/code]

To allow validation information to be displayed, we made several changes to this file and to our web application. These changes are listed here:

  • Adding the Seam UI tag library to the header of the JSF page.
  • Specifying which objects need to be validated, by using the  or tags.
  • Defining the three different facets that specify the formatting and output of the error message for each field. These facets must be surrounded by the  tag.
  • Adding the Seam and third-party JARs into the WEB-INF/lib directory of the web application.

The JSF messages collection

So far, we’ve only added messages to the JSF messages collection via Hibernate validators that are applied to entities within our domain model. Sometimes, it can be useful to add a message that can be displayed irrespective of any errors or input controls on a form to the messages collection. The JSF messages collection is one of Seam’s in-built components and is named org.jboss.seam.faces.facesMessages.

[code lang=”java”]
@Name(‘org.jboss.seam.faces.facesMessages’)
[/code]

This in-built component can easily be accessed within Seam applications by using the FacesMessages().instance() method. For example:

[code lang=”java”] FacesMessages.instance().add(‘Phew, that was a lot of maths !!’);
[/code]

If we add all of our Hibernate validators to our Calculator.java class, the code will look as follows:

[code lang=”java”] package com.davidsalter.seamcalculator;
import java.io.Serializable;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.faces.FacesMessages;
import org.hibernate.validator.Max;
import org.hibernate.validator.Min;
import org.hibernate.validator.Range;

@Name(‘calculator’)
public class Calculator implements Serializable {
private double value1;
private double value2;
private double answer;
@Min(value=0)
@Max(value=100)
public double getValue1() {
return value1;
}

public void setValue1(double value1) {
this.value1 = value1;
}
@Range(min=0, max=100)
public double getValue2() {
return value2;
}
public void setValue2(double value2) {
this.value2 = value2;
}
public double getAnswer() {
return answer;
}
public void add() {
this.answer = value1 + value2;
//Access the ‘org.jboss.seam.faces.facesMessages’ component
and add a message into it.
FacesMessages.instance().add(‘Phew, that was a lot of
maths !!’);
}
}
[/code]

In this code, we have added validators to the input data and then added a custom message into the JSF messages collection, to be displayed when a successful calculation was performed.

Building and testing the validating Seam calculator

In order to build and test the validating Seam calculator, we need to copy the additional JAR files (namely, hibernate-validator.jar, jboss-el.jar, jboss-seam-ui.jar, jsf-api.jar, and jsf-impl.jar) into the /lib directory of the sample project.

A second sample project—Seam Validating Calculator—is available
in the code bundle for this chapter.

To build and deploy the project onto the JBoss Application Server, we need to execute the deploy ant target.

seam-13To view the application in the browser, navigate to http://localhost:8080/SeamCalculator/calc.seam.

If any invalid data is entered into the web application, this is picked up by the Hibernate validators and displayed on the form, both next to the field containing the error and in a list at the bottom of the page, which shows all of the errors on the page.

seam-13In the previous screenshot, you can see that the Hibernate validator has done its job correctly and added an error message informing the user that Value 2 is invalid as abc is not a valid number. While this is technically correct, the error message is very
user-unfriendly and would probably result with many unhappy customers! Later on in this book, we will look at how this error message can easily be changed in a localizable fashion so that an appropriate error message can be displayed in different languages for different users. For the moment, the important thing to note is that we have performed validation on user input and provided an error message when the validation fails.

When valid information is entered into the fields and the Add button is clicked, the two inputs are added together and displayed along with a custom error message that was added to the JSF messages collection.

seam-14

Summary

In this chapter, we’ve taken our first real steps into developing Seam applications. We’ve looked into Seam components and learned that they are declared with the @Name annotation. We’ve seen how we can inject and outjet Seam components by using the @In and @Out annotations respectively. After learning about Seam components, we wrote a simple Seam application using these concepts, which shows the layout for Seam applications.

In the second half of this chapter, we looked at how to add validation to Seam components and how to display validation errors and special messages on web pages, both around input components and in a list on the page.

In the sample application that we built in this chapter, everything took place within a single JSF page. In the next chapter, we’ll look at page fl ow within Seam applications, and show how we can easily build up complex routing mechanisms to navigate between pages.

Filed Under: JBoss Seam Tagged With: JBoss Seam

Introduction to JBoss Seam

June 21, 2007 by Krishna Srinivasan Leave a Comment

1) Introduction

Yet another Web Application Framework! This time it is from JBoss Community. JBoss provides a new Web Application Framework called “JBoss Seam” which combines the advantages from the two rapidly growing technologies Enterprise Java Beans 3.0 and Java Server Faces. JBoss Seam, by sitting on top of J2EE provides a nice way of integration between JSF and EJB Components with other great functionalities. This article is an introductory article only and it covers the idea that gave birth to JBoss Seam, its advantages, the various modules involved along with a Sample Application. This article assumes the readers to have some bit of knowledge and programming in areas like Java Server Faces and Enterprise Java Beans 3.0. For more information about these technologies, visit JSF and EJB 3.0.

2) The Need for JBoss Seam

Let us exactly define what JBoss seam is. JBoss Seam provides a Light-weight Container for J2EE standards and it addresses the long-standing issues in any Typical Web Application like State Management and Better Browser Navigation. It also neatly provides an integration between the two popular technologies, Java Server Faces (in the UI tier) and Enterprise Java Beans (EJB 3 in the Server Side). Before getting into the various details about JBoss Seam let us see the common set of problems that are being faced in a Development and the Usability of a typical Web Application using Java Server Faces and Enterprise Java Beans.
For this, let us assume an imaginary application. Let us keep the requirements of the imaginary Web Application we are going to consider very small. The Web Application is a simple Registration Application, which provides the user with a View which contains username and password text-fields. User can click the submit button after filling both the fields. If the username password information given by the user is not found in the database, the user is assumed to be a new user and he is greeted with a welcome message; else an error page is displayed with appropriate message.
Let us analysis the roles of JSF and EJB 3.0 in this Web Application. More specifically, we will analysis the various components in both the client as well the server tier along with their responsibilities.
In the Client side, for designing and presenting the form with the input controls (text-field and button) to the user, we may have written a userinput.jsp page with the set of JSF core tag libraries like <f:view> and <h:form>. And then, a JSF Managed Bean called UserBean encapsulated with properties(username and password) may have been coded which serves as a Model. The UI components values within the JSP page would have got bound to the properties of the Managed Bean with the help of JSF Expression Language. Since the logic is to query from the database for the existence of the username and the password, a Stateless Session Facade Bean would have been written whose sole purpose is to persistence the client information to the database. For persistence the information, the Session Bean may depend on the EntityManager API for querying and persisting entities.
The Data Traversal Logic from JSF to EJB Session Bean should have be taken care by the Managed Bean only. The Managed Bean apart from representing a Model may also act as a Listener in handling the button click events. Say, after clicking the register button, one of the action methods within the Managed Bean would have been called by the framework, and here the Bean might have a JNDI Look-up to get an instance of the Session Bean to persisting or querying the user information. If we look at carefully, the JSF Managed Bean is serving as an intermediary between the transfer of Data from the Client to the Server. Within this Managed Bean is the code for getting a reference to the Session Bean for doing various other functionalities. Wouldn’t a direct commnication between JSF UI Components and the Enterprise Bean Components be nice? There is no purpose of the intermediate Managed Bean in this case. JBoss Seam provides a very good solution for this. Not only this many of the outstanding problems that are faced in a Web Application are also addressed and given solution in this Framework.

3) Advantages of JBoss Seam

Following are the major advantages that a Web Application may enjoy if it uses JBoss Seam Framework. They are

  • Integration of JSF and EJB
  • Stateful Web Applications
  • Dependency Bijection Support

Let us look into the various advantages of JBoss Seam in the subsequent sections.

3.1) Integration of JSF and EJB

Today the Web Application World see more and more matured technologies that are focusing to establish an easy-to-use development by reducing lots and lots of boiler-plate code along with some other added functionalities in their own domains. Let us consider JSF and EJB technologies to extend further discussion regarding this.
EJB 3.0 which is a specification given from Sun has gained much popularity because of its simplified yet robust programming model. Much of the middle-ware related services like Security, Transactions, Connection Pooling etc is delegated to the container itself. Comparing to its predecessors, EJB 3.0 offers a POJO programming Model. No need for your beans to extend or implement EJB specific classes or interfaces. And also, along with the new specification Java Persistence API (JPA), an unified programming model to access the underlying database along with rich set of features are now possible thereby completely eliminating the heavy-headed entity beans.
What is JPA?:Java Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) and Hibernate (from JBoss). One of the great benefits of JPA is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications.
Java Server Faces provides a Component-based approach for developing User Interface Components in a Web Application. It hides most of the boiler-plate code and provides a higher-level abstraction over the client request and the server response objects. Using Java Server Faces, a Web Application can be viewed by components making events and listeners executing the appropriate logic for the Events. No need for the traditional HttpServletRequest and HttpServletResponse object to extract the client input parameters and to generate the response.
JBoss provides a framework in which the Events that are emitted by the JSF UI Components can be directly handled by the Enterprise Beans. No need for the intermediate Managed Beans which establishes the data transfer from and to JSF and EJB.

3.2) Dependency Bijection Support

Before getting into Dependency Bijection, it is wise to look at the two types: namely Dependency Injection and Dependency Outjection. These two are the popular patterns and modern Frameworks and Containers makes use of this abundantly. Let us see these two techniques

3.2.1) Dependency Injection
This model is used when a Component or a Service which is running inside some Framework or a Container is well known in the early stages so that the Framework/Container can create instances of them thereby taking the burden from the Clients. These type of model is used heavily in most of the J2EE Components, to name a few, EJB, Servlets, JMS etc.
For example, consider the following piece of code,
MySessionBean.java

[code lang=”java”]@Stateless
public class MySessionBean{

@PersistentContext
private EntityManager entityManager;

public void query(){
// Do something with EntityManager reference.
}
}[/code]

In the above code, the Session Bean (MySessionBean) is depending on the services of EntityManager. So, before the session bean starts using the EntityManager object, the EntityManager instance should be available. This is made simple because the EJB Container will creates a new instance of the EntityManager object based on the various parameters taken from the Configuration File and injects this instance to the EntityManager reference. This way of doing is called Dependency Injection.
In Seam, injection of a Component by the Seam framework is done by the use of @In Annotation. For example, consider the following piece of code,
MyComponent.java

[code lang=”java”]public class MyComponent{

@In
private MyInjectorComponent compToBeInjected;

}[/code]

When the Application gets deployed, Seam Framework will keep track of these Annotated Components and during run-time, upon creation of MyComponent class and before the invocation of any other methods, the Container will inject and instance of an object of type MyInjectorComponent to the compToBeInjected reference.

3.2.2) Dependency Outjection
In Dependency Injection, usually the Framework injects the services to components that are in need of, whereas the reverse happens in Dependency Outjection. Consider the following piece of code,
MyComponent.java

[code lang=”java”]public class MyComponent{

@Out
private MyService myService;

public MyComponent(){
}

public MyService getMyService(){
return createMyService();
}

private MyService createMyService(){
// My own way of creating
}
}[/code]

MyServiceClient.java

[code lang=”java”]public class MyServiceClient{

@In
private MyService myService;

}[/code]

In the above code, MyComponent class is acting as a factory class for creating MyService objects. Assume that this MyComponent class is a controlled class meaning that is being managed by the Container or the Framework wherever it is embedded. Situations may arise such that the MyService object might be needed by the Container so that the Container can use this MyService to inject dependencies on other components or clients. For instance, MyServiceClient is in need of MyService object and the Container can inject this reference from the object that it has taken from MyComponent class. This model is Dependency Outjection where a Service is taken by the Container from the Component.
Seam supports both these models in the form of @In and @Out annotations. For example consider the following class,
MyClass.java

[code lang=”java”]public class MyClass{

@In
private MyServiceOne service1;

@out
private MyServiceTwo service2;
}[/code]

The above code can be read like this. The container injects the reference to service1 because it is annotated with @In (meaning for Injection). And at a later stage, the Container may taken the reference of service2 (because of @Out) thereby serving it to other needful Components.

3.3) Stateful Web Applications

Since the underlying protocol used in a Web Application is Http, all Web Application are Stateless in nature. Precisely it means that all the requests that are coming from the Client Browser are treated as individual requests only. The Server shows no partiality for the Client Requests. It is up to the Application or the Framework to identify whether requests are coming from the same Client or not. Session Management in Web Application is a time-consuming job and typically Servlets/Jsp provides various ways to manage sessions. Even in this case, Application Developers still have to depend on HttpSession like classes for creating session objects and storing/retrieving objects from the session.
JBoss Seam provides an excellent way to Manage States amongst multiple client requests. The State Management Facility is tightly integrated with Seam Components in the form of various Contexts. Following are the most commonly used Contexts in Seam.

  • Conversation – A Conversation generally represents multiple requests that come from the same client. Components that come under this category can remember the state of the client and this forms the heart of State Management in Seam.
  • Application – This context generally holds information that is used by various components within the same Application.
  • Session – Components that fall under this category simply uses Http Session Api for state management.
  • Page – The scope of the components managing the information is restricted to the Current Page only. All the stored information is lost when the user leaves this current page.
  • Stateless – Components that falls under this category don’t manage state between multiple Client Requests.

4) Seam Components

Components in Seam take over the functionality as well the Business Logic in a Web Application. The good thing is that all Seam Components are POJO Objects only meaning that Components don’t have to extend or implement any Seam specific Classes or Interfaces. The Seam Component Model follows the standard Java Bean Component Architecture. Even it is possible to Annotate Enterprise Beans (Session Beans, Entity Beans and Message Driven Beans) as Components. Seam provides an excellent framework for Integrating Enterprise Beans into the Seam Framework.
As mentioned before, Components in Seam carries the business process involved in a typical Web Application. Seam Components may also act as Listeners for JSF UI Components or they may even interact with the Database. Since Seam provides a good deal of Integration with EJB Components, Developers generally prefer having Stateful Session Beans as Listeners and the Entity Beans for interacting with the Database.
Usually Seam Components are identified by Name, Scope and Role. These are Declarative Identifications meaning that they are represented directly in the Source Code with the help of Annotations. For example, consider the following Seam Component,
MyStatefulBeanImpl.java

[code lang=”java”]@Stateful
@Name("MyStatefulBean")
@Scope(ScopeType.SESSION)
public MyStatefulBeanImpl implements MyStatefulBean{

public String statefulMethod(){
}
}[/code]

In the above code, the @Name Annotation represents the name of a Seam Component using which other Managed Seam Components can access it. @Scope defines how life this Component will survive during the Web Application. Since the above class is actually a Session Bean, it has been marked with @Stateful Annotation.

5) Support for Annotations

Most of the boiler-plate needed for the various parts of the Application is taken care by the Seam because of the declarative style of programming available in the form of Annotations. Most of the Annotations that we see in Seam are a mix of EJB 3.0 and Seam specific Annotations. They are a number of Annotations defined in the Seam Api and this section just provides an overview of the most commonly used Annotations. For a complete list of Annotations and their purpose, have a look at the Seam Documentation.

5.1) Annotations for Seam Components

Components in Seam are really POJO’s and they play a major role in keeping the Application stateful. Following are the most commonly used Annotations related to Seam Components are given below.

  • @Name
  • @Scope
  • @JndiName

5.1.1) @Name Annotation
This Annotation specifies the name of a Seam Component so that other Components (Seam Components or JSF Pages) can refer the Component by its name. This Annotation is mandatory for a class that is going to act as a Seam Component. Following is an example of the Seam Component.
MyComponent.java

[code lang=”java”]@Name("MyComponent")
public class MyComponent{
// Some Functionalities here.
}[/code]

5.1.2) @Scope Annotation
This Annotation, if given, tells to the Seam Framework about the scope (or the life-time) for a Seam Component. The values for this Annotation are taken from the org.jboss.seam.ScopeType Enum and can be any of the following values: APPLICATION, CONVERSATION, SESSION, PAGE, STATELESS etc. Following is a sample code snippet for using the @Scope Annotation.
MyComponent.java

[code lang=”java”]@Scope(ScopeType.SESSION)
@Name("MyComponent")
public class MyComponent{
// Some Functionalities here.
}[/code]

5.1.3) @JndiAnnotation Annotation
This Annotation should not be applied to normal Seam Components but to Components that represent any of EJB or JMS Service. Following is an example of one such component.
MySessionBean.java

[code lang=”java”]@JndiName("ejb/session/MySessionBean")
Public class MySessionBean{

}[/code]

5.2) Annotations for Components Lifecycle

All Components in Seam have well defined Life-cycle Management as defined by the Seam Framework. Management of Component Life-cycle is important as it has dependencies over the state Management of Web Applications. Following are the most commonly used Annotations for Life-cycle Management.

  • @Create
  • @Destroy

5.2.1) @Create Annotation
When a method inside a Seam Component is marked with @Create Annotation, then this method will be called immediately after the creation of Seam Component. Most of the costly Resources like Initializing File or Database can be coded in this method. Following is the sample code snippet for the same,
MyDatabaseUtils.java

[code lang=”java”]@Name("MyDatabaseUtils")
Public class MyDatabaseUtils{

@Create()
public void initDatabase(){
}
}[/code]

5.2.2) @Destroy Annotation
If @Create Annotation for a Seam Component deals with initialization Stuffs for a object, then the code inside the @Destroy Annotation can be used to Release Resources or References to other objects. This method will be called before a Component is going to get removed from any of the Context as mentioned by its Scope.
MyDatabaseUtils.java

[code lang=”java”]@Name("MyDatabaseUtils")
Public class MyDatabaseUtils{

@Destroy()
public void closeDbResources(){
}
}[/code]

6) Events

Events can occur in a Seam Application through various Sources. And the events emitted by the Sources are captured and handled by the Listeners. Let us look into the various Sources that are responsible for emitting Events. Source can be any one of the following items.

  • Seam Page Events
  • Seam Component Driven Events
  • JSF Components Emitting Events

Let us look into the details one by one.

6.1) Seam Page Events

Before Seam renders a page to Display, it checks whether the page has registered itself for firing any Events. If that’s the case, then the Framework will fire Events on behalf of the Web Pages. For example, consider the following situation. If the Home Page of a Web-site is eager to display the hits to this page, then the following could be possible,
pages.xml

[code lang=”xml”]
<pages>
<page view-id = "/hit-count.jsp" action = "#{Hitter.initHits}">
</page>
</pages>
[/code]

The above is the pages.xml file and it should be placed in the WEB-INF directory of the Web Application module. The above code essentially tells that whenever a request comes for /hit-count.jsp, then call the method initHits() available in the Hitter class.

6.2) Seam Component Driven Events

It is possible by the Seam Components also to emit Events. There is a Low-degree of Coupling between the Initiation and the Handling of Events. Even Custom Events can be declared specified either in the Xml File or through Annotations. For example, consider the following code snippet,

components.xml

[code lang=”xml”]
<components>
<event type = "myEvent">
<action expression = "#{MyComponent.myCallBack1}"/>
<action expression = "#{MyComponent.myCallBack2}"/>
</event>
</components>
[/code]

The above Xml File must be placed in the WEB-INF directory of the Web Application Module. If anyone raises an Event of type ('myEvent' is just a string), then the following methods defined inside the action element will be fired. For, example, consider the following code,

MyEventInitiator.java

[code lang=”java”]public class MyEventInitiator{

public void initEvent(){
Events.instance().raiseEvent("myEvent");
}
}[/code]

MyComponent.java

[code lang=”java”]public MyComponent{

public void myCallBack1(){
System.out.println("My Call back method 1 called");
}

public void myCallBack2(){
System.out.println("My Call back method 2 called");
}
}[/code]

If some one initiates the Event by calling MyEventInitiator.initEvent(), then a event of type myEvent gets raised. Since this Listeners (Actions) of this Event are defined in the components.xml file in the form of MyComponent.myCallBack1() and MyComponent.myCallback2(), both these methods will be fired in the order in which they are defined.

6.3) JSF Components Emitting Events

As discussed previously, Seam components can act as Listeners for the JSF UI Components emitting Events. For example, consider the following piece of Code,
calculate.jsp

[code lang=”html”]
<h:commandButton value = "Calculate Tax" action = "#{TaxCalculator.calculateTax}">
</h:commandButton>
[/code]

In the above snippet code, whenever the User clicks the Calculate Tax button, the calculateTax() method defined inside the TaxCalculator class will be called. Following is how the TaxCalculator component looks like,

TaxCalculator.java

[code lang=”java”]
@Name("TaxCalculator")
@Scope(ScopeType.PAGE)
public class TaxCalculator{

public void calculateTax(){
}
}[/code]

7) Sample Application

With the concepts and theories in mind, let us develop a minimal functionality Shopping Application using JBoss Seam Framework. The following are the list of softwares/products needed for the Sample Application to work.

The functionality of the Shopping Application is simple. It initially provides a page prompting for the user name before beginning the Shopping Application. Then a List of products along with Product Id, Name, Description, Price, Number of Items to be checked-out are shown to the user. The user can select the product items he wants and continues to check-out. After that a brief summary of the Product Information is shown to the User .
Since the Shopping Application it is an Enterprise application, it involves the Creation of Jar and War files and then packaging them as an Ear File. Let us look into the various files and the directory structure required for completing this Application.

7.1) View Files

These set of files represents the view files rendered as a result of client making the client. Let us look into the various files involved one by one.

7.1.1) index.html
index.html

[code lang=”html”]
<html>
<head>
<meta http-equiv="Refresh" content="0; URL=user.seam">
</head>
</html>
[/code]

This is the file that will be request when the client starts the Application in the Web Browser. This file immediately redirects to user.seam. Later, we will see that the extension seam is mapped to xhtml (for Facelets). Here is the content of user.xhtml.

7.1.2) user.xhtml

[code lang=”html”]
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">

<body>

<center>
<h2>Welcome to Shopping.</h2>
</center>

<h:form>
<center>

To contine shopping, Please enter your name:
<br/>

<h:inputText value="#{User.name}" size="20"/><br/>
<h:commandButton type="submit" value="Continue Shopping" action="product-list"/>

</center>
</h:form>

</body>
</html>
[/code]

The things to note that is there is a Component called User with a property called name. As mentioned in the preceding sections, the user will be prompted to enter his name before continue with the shopping. The entered name will be mapped to the name property in the User class. Also note that when the clicks the “Continue Shopping” button, the action is re-directed to “product-list” which actually maps to product-list.xhtml (which is defined the navigation.xml) file. Given below are the contents of product-list.xhtml file.

7.1.3) product-list.xhtml

[code lang=”html”]
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">

<body>

<center>
<h2>List of available products</h2>

Hi, <b>#{User.name}</b>
Following are the available producst in our shopping repository
</center>

<h:form>

<center>
<h:dataTable columnClasses="list-column-center, list-column-right,
list-column-center, list-column-right" headerClass="list-header"
rowClasses="list-row" styleClass="list-background"
value="#{ShoppingManager.products}" var="aProduct">

<h:column>
<h:outputText value = "#{aProduct.id}"/>
</h:column>

<h:column>
<h:outputText value = "#{aProduct.name}"/>
</h:column>

<h:column>
<h:outputText value = "#{aProduct.description}"/>
</h:column>

<h:column>
<h:outputText value = "#{aProduct.price}"/>
</h:column>

<h:column>
<h:inputText value = "#{aProduct.noOfItems}" size = "5"/>
</h:column>
</h:dataTable>
</center>

<center>
<h:commandButton action="#{ShoppingManager.checkout}"
value="Checkout Products"/>
<h:commandButton action="user" value="Go to user page" type = "submit"/>
</center>

</h:form>
</body>
</html>
[/code]

Note that a class called Product with properties name, description, price, noOfItems, amount, id (Primary key) is defined which represent of the products in the shopping repository. Access to the product objects such as displaying is facilitated with the help of ShoppingManager Session Bean. Note that this Session Bean is configured to act as a Seam Component in this Application. As soon as this page loads, all the Product information from the Products Table, is fetched and it is displayed in this page.
We have two buttons at the bottom of the page. One is to navigate to the Home page and the other is to checkout the products. As soon as the user clicks the “Checkout Products” button, the checkOut() method in the ShoppingManager bean is fired which will calculate the amount of the individual products the user has selected. Upon completion of the method, checkout action is returned which is mapped with product-summary.xhtml page as defined in the navigation.xml file.

7.1.4) product-summary.xhtml
Given below are the contents of product-summary.xhtml file which will display the summary information of the user selected products along with the total price information.
product-summary.xhtml

[code lang=”html”]
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">

<body>

<center>
<h2>Shopping Summary</h2>
Hi, <b>#{User.name}</b>
</center>

<h:form>
<center>
<h:dataTable columnClasses="list-column-center, list-column-right,
list-column-center, list-column-right" headerClass="list-header"
rowClasses="list-row" styleClass="list-background"
value="#{ShoppingManager.products}" var="aProduct">

<h:column>
<h:outputText value = "#{aProduct.id}"/>
</h:column>

<h:column>
<h:outputText value = "#{aProduct.name}"/>
</h:column>

<h:column>
<h:outputText value = "#{aProduct.description}"/>
</h:column>

<h:column>
<h:outputText value = "#{aProduct.price}"/>
</h:column>

<h:column>
<h:outputText value = "#{aProduct.noOfItems}" size = "5"/>
</h:column>

<h:column>
<h:outputText value = "#{aProduct.amount}" size = "5"/>
</h:column>

</h:dataTable>
</center>

<center>
Total Price:
<b><h:outputText value = "#{ShoppingManager.totalPrice}" /></b>
Happy Shopping.
<h:commandButton action="user" value="Go to user page" type = "submit"/>
</center>

</h:form>
</body>
</html>
[/code]

7.2) Resource Files

In Seam terms, all the Configuration Information (web.xml, application.xml) and the various Resources Messages are defined in terms of resources. Let us have a look into the various Configuration file.

7.2.1) application.xml
application.xml

[code lang=”xml”]
<application>
<display-name>Seam Hello World</display-name>

<module>
<web>
<web-uri>app.war</web-uri>
<context-root>/Shopping</context-root>
</web>
</module>

<module>
<ejb>app.jar</ejb>
</module>

<module>
<java>jboss-seam.jar</java>
</module>

<module>
<java>el-ri.jar</java>
</module>

<module>
<java>el-api.jar</java>
</module>

</application>
[/code]

This is the Application Level Configuration File which contains entries for the Web and the Java Module along with the libraries that are specific to JBoss and Seam.

7.2.2) ejb-jar.xml
ejb-jar.xml

[code lang=”xml”]
<ejb-jar>
<assembly-descriptor>
<interceptor-binding>
<ejb-name>*</ejb-name>
<interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class>
</interceptor-binding>
</assembly-descriptor>

<interceptors>
<interceptor>
<interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class>
</interceptor>
</interceptors>
</ejb-jar>
[/code]

These entries are necessary to make all the Ejb Components look like Seam Components. This is achieved by intercepting the functionality of the Ejb Components with the help of Interceptors.

7.2.3) persistence.xml
persistence.xml

[code lang=”xml”]
<persistence>
<persistence-unit name="ShoppingManager">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/DefaultDS</jta-data-source>

<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.transaction.flush_before_completion" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
[/code]

The above file represents the Persistence Unit that the Session Bean may use to store and retrieve information about the product Objects from the Product table. A persistence Unit generally contains information about its Database, Driver Name, Dialect etc.

7.2.4) components.xml
Since we are using Session Bean for interacting with the Entity Object, we must specify the Jndi Name of the Session Bean so that Seam framework can lookup and create an instance of the Session Bean. This is achieved with the help of the following Xml File.
components.xml

[code lang=”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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://jboss.com/products/seam/core
http://jboss.com/products/seam/core-1.1.xsd
http://jboss.com/products/seam/components
http://jboss.com/products/seam/components-1.1.xsd">

<core:init jndi-pattern="Shopping/#{ejbName}/local" debug="true"/>
<core:manager conversation-timeout="120000"/>

</components>
[/code]

7.2.5) navigation.xml
All the navigation rules in this Shopping Application are logically expressed in terms of action in this navigation.xml file. The advantage of providing this kind of declarative mapping is that all the components will refer only to the Logical Outcome of the Action and not the Physical Location of the Page.
A.a

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

<faces-config>

<navigation-rule>
<from-view-id>*</from-view-id>

<navigation-case>
<from-outcome>user</from-outcome>
<to-view-id>/user.xhtml</to-view-id>
<redirect/>
</navigation-case>

<navigation-case>
<from-outcome>product-list</from-outcome>
<to-view-id>/product-list.xhtml</to-view-id>
<redirect/>
</navigation-case>

<navigation-case>
<from-outcome>checkout</from-outcome>
<to-view-id>/product-summary.xhtml</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>

</faces-config>

[/code]

7.3) Source Files

Now let us look into the Various Java Source Files (representing Session Beans, Entities, etc). Following is the code for the Product Entity.

7.3.1) Product.java
Product.java

[code lang=”java”]package net.javabeat.articles.jboss.seam.shopping;

import org.jboss.seam.annotations.*;
import javax.persistence.*;
import java.io.Serializable;

import static org.jboss.seam.ScopeType.SESSION;

@Entity
@Name("person")
@Scope (SESSION)
public class Product {

private String name;
private String description;
private double price;
private int noOfItems;
private double amount;
private long id;

public Product() {
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public double getPrice() {
return price;
}

public void setPrice(double price) {
this.price = price;
}

public int getNoOfItems() {
return noOfItems;
}

public void setNoOfItems(int noOfItems) {
this.noOfItems = noOfItems;
}

public double getAmount(){
return amount;
}

public void setAmount(double amount){
this.amount = amount;
}

@Id @GeneratedValue
public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}
}[/code]

Note that apart from qualifying this as an Entity, it has to be qualified with Annotations like @Name and @Scope to tell to the Seam Framework that it is a Seam Component. The Session Bean will store and retrieve the values from the Product objects fetched from the Product Table.

7.3.2) Session Bean Interface
Following is the interface definition of the Session Bean. This Bean has various functionalities like Creating, Retrieving and Destroying products. Other that this it also performs the checkout operation which is nothing but the calculation of the no of items with the individual products along with the total amount calculation.
Shopping.java

[code lang=”java”]package net.javabeat.articles.jboss.seam.shopping;

import javax.ejb.*;
import java.util.*;
import net.javabeat.articles.jboss.seam.shopping.Product;

@Local
public interface Shopping {

public List getProducts();
public void createProducts();
public void destroyProducts();
public String checkout();
public double getTotalPrice();

}[/code]

7.3.3) Session Bean Implementation
ShoppingManager.java

[code lang=”java”]package net.javabeat.articles.jboss.seam.shopping;
import java.util.List;
import javax.ejb.*;
import net.javabeat.articles.jboss.seam.shopping.Product;
import net.javabeat.articles.jboss.seam.shopping.ProductDatabase;
import org.jboss.seam.annotations.*;
import org.jboss.seam.ejb.*;

import static org.jboss.seam.ScopeType.SESSION;

import javax.persistence.*;

@Stateful
@Name("ShoppingManager")
@Scope (SESSION)
public class ShoppingManager implements Shopping {

private List products;
private double totalPrice;

@PersistenceContext(unitName = "ShoppingManager")
private EntityManager entityManager;

@Create
public void createProducts () {

Product product = null;
product = createProduct("Sony Playstation",
"Gaming Console The Sony Playstation 2", 9000d, 0);
entityManager.persist(product);

product = createProduct("Traffic Signal – DVD",
"SKU-CODE: Traffic Signal – Sony &amp; BMG", 240d, 0);
entityManager.persist(product);

product = createProduct("DVD Player",
"Samsung P475 DVD Player", 3990d, 0);
entityManager.persist(product);

product = createProduct("COMPAQ Notebook",
"COMPAQ Notebook PC – PRESARIO V6307", 49000d, 0);
entityManager.persist(product);

products = entityManager.createQuery(
"select prdt from Product prdt").getResultList();
}

private Product createProduct(String name, String description,
double price, int noOfItems){

Product product = new Product();
product.setName(name);
product.setDescription(description);
product.setPrice(price);
product.setNoOfItems(noOfItems);
return product;
}

public List getProducts() {
return products;
}

public String checkout(){
for(Product aProduct : products){
aProduct.setAmount(aProduct.getNoOfItems() * aProduct.getPrice());
totalPrice = totalPrice + (aProduct.getNoOfItems() * aProduct.getPrice());
}
return "checkout";
}

public double getTotalPrice(){
return totalPrice;
}

@Destroy
@Remove()
public void destroyProducts(){
}
}[/code]

As already explained, the above code makes use of EntityManager to create and retrieve products from the products Table.

8) Conclusion

This is an Introduction article about the evolving JBoss Seam Framework. It started with the necessity of having this Framework and then continued with the discussion of having some many advantages of using this framework. The advantages like “EJB-JSF” Integration, the need for a Stateful Web Application and the exiting Dependency Bijection Functionality is covered in much detailed manner. Then the various core modules of the Seam Framework like Seam Components, the need and the usage of Seam Annotations over various modules along with the Various Types of Events emited by Seam Sources are given much consideration and discussed briefly. Then the article finally ended up with a Shopping Application thereby illustrating the various techniques and concepts available in JBoss Seam.

Filed Under: JBoss Seam Tagged With: JBoss Seam

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved