Over a million developers have joined DZone.

Defne, RichFaces, JSF, JPA and CDI: Nice Combo for Java EE Web Application

DZone's Guide to

Defne, RichFaces, JSF, JPA and CDI: Nice Combo for Java EE Web Application

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

Defne is a service oriented web application framework. The main motivation behind Defne is ease of use. Defne allows developers to concentrate on their business logic while it provides all other application requirements such as transaction and security. With Defne, you can implement Java EE based business logics easily.

RichFaces is a component library for JSF and an advanced framework for easily integrating AJAX capabilities into business applications.

Apache OpenWebBeans/CDI is a  Contexts and Dependency Injection for the Java EE platform.

In this article, we are going to see how one implements a real  Java EE web application using JBoss RichFaces, Apache OpenWebBeans  and Defne libraries together. While RichFaces provides powerful AJAX capable GUI components, Defne provides implementation of the business services with service oriented fashion.  Never need a bunch of configuration files for JSF managed beans, because all of the bean creations and dependecy injections are handled by OpenWebBeans, thanks to Java EE standards!


In this article we use SIwpas, http://code.google.com/p/siwpas, Simple Web Profile Application Server that contains all necessary libraries. If you wish to use Tomcat, Jetty or any other application server, you have to bundle necessary libraries with your application or server classpath.

Defne libraries can be downloaded from  http://code.google.com/p/defne/. JBoss RichFaces libraries can be downloaded from http://jboss.org/richfaces.

In this application, we use maven tool for or build tool. All dependencies of the application are defined in "pom.xml" files.

Sample Web Application

In this article, our application is a reservation web application that provides the following features;

  • Registration of users, (admin and normal users)
  • Admin user defines hotels and search for reservations,
  • Normal users can reserve hotels, update informations etc.
  • Security is handled by JSF phase listener approach
Here is the login page of the application,


And reservation page for the normal user. We use this page for the article. Here you see JBoss RichFaces Panel, Menu and Date components.

Modules of The Application

Application is architectured as several layers,

  • GUI Layer           : It contains JSF managed beans (actually CDI managed beans). Those beans are used by JSF pages via EL expressions,
  • Model Layer       : It contains JPA entity classes and JPA main configuration file i.e, persistence.xml,
  • Utility Layer       :  It contains utility classes that are used by all other layers,
  • Business Layer : It contains Defne Business Services that are interacted with backend database.

GUI Layer
This layer contains JSF/CDI managed beans. They have connected with JSF page using Expression Language method/value binding expressions. For example, following is the part of the "UserReservationBean"  that is ConversationScoped CDI managed bean.

public class UserReservationBean implements Serializable


private @Inject @PojoExecutorProxy IServiceExecutorProxy serviceExecutor;

private @Inject Conversation conversation;

private @Inject SessionTracker tracker;

public UserReservationBean()


public String addReservation()
if(getReservationDate() == null)
JSFUtility.addErrorMessage("Reservation date can not be empty!", "");
return null;


JSFUtility.addInfoMessage("Reservation conversation with started with id : " + conversation.getId(), "");

Hotel hotel = (Hotel)model.getRowData();

SelectItem item = new SelectItem();

if(contains(item.getValue()) != null)
JSFUtility.addErrorMessage("Given hotel is already added", "");

return null;


ReservationModel model = new ReservationModel(hotel.getId(),reservationDate);
models.put(item.getValue().toString(), model);

return null;

public String checkout()
JSFUtility.addErrorMessage("Conversation is not running! Please add hotel for reservation", "");
this.reservationDate = null;
Message inBag = MessageFactory.newMessage(IUserService.SERVICE_NAME,IUserService.ADD_RESERVATION.METHOD_NAME);
inBag.putMessageParameter(IUserService.ADD_RESERVATION.INPUT.RESERVATIONS, models);
inBag.putMessageParameter(IUserService.ADD_RESERVATION.INPUT.ID, tracker.getUser().getId());



JSFUtility.addInfoMessage("Reservation are completed succesfully. Conversation with id "+conversation.getId() + " is ended ", "");


this.reservationDate = null;

return null;

UserReservationBean is a @ConversationScoped bean. Developers start conversation with Conversation.begin() method and end its lifecycle with Conversation.end() method. Here, user adds hotels into the list and starts the conversation,  if  it has not been already started. When user checks out(clicks checkout button) the reservations, conversation is ended/destoyed at the end of the current JSF request and hotels are reserved for the user. Conversations enable the users to open different tabs on the same internet browser page!!!

Each conversation has an unique id for current user session. Under the hood, each conversation instance is saved in user session with those unique conversation ids.

The conversation context is provided by a built-in context object for the built-in passivating scope type @ConversationScoped. The conversation scope is active:

  • During all standard lifecycle phases of any JSF faces or non-faces request
The conversation context provides access to state associated with a particular conversation.

Most important part is the @Injection part and service execution part,

  • @Inject @PojoExecutorProxy IServiceExecutorProxy serviceExecutor: Injected for executing Defne Services.
  • @Inject Conversation conversation : Injected for managing conversation state
  • @Inject SessionTracker tracke : Injected for getting the current user information

SessionTracker is a session scoped CDI bean that contains user information,

public class SessionTracker implements Serializable
private static final long serialVersionUID = 6365740106065427860L;

private User user;

* When event fires, this observer method is called
* by the {@link BeanManager} interface.
* @param loggedInEvent event
public void userAdded(@Observes LoggedInEvent loggedInEvent)
this.user = loggedInEvent.getUser();

public User getUser()
return this.user;

* @param user the user to set
public void setUser(User user)
this.user = user;


Here you see @Observes annotation. This is provided by CDI specification for implementing Event-Observer pattern. When user is logged into the system, this method is called by the container. Here is the logged-in process,

public class LoginBean
/**User name*/
private String userName;

private String password;

/**Inject of the event instance*/
private @Inject @Any Event<LoggedInEvent> loggedInEvent;

/**Database related login controller*/
private @Inject @PojoExecutorProxy IServiceExecutorProxy serviceExecutor;

* Check user login.
* @return navigation result
public String login()
if(GenericValidator.isBlankOrNull(userName) || GenericValidator.isBlankOrNull(password))
JSFUtility.addErrorMessage("User name and password fields can not be empty", "");

return null;

Message inBag = MessageFactory.newMessage(LoginService.LOGIN_SERVICE.SERVICE_NAME,

inBag.putMessageParameter(LoginService.LOGIN_SERVICE.CHECK_LOGIN_METHOD.USER_NAME, userName);
inBag.putMessageParameter(LoginService.LOGIN_SERVICE.CHECK_LOGIN_METHOD.PASSWORD, password);

inBag = this.serviceExecutor.execute(inBag);

if(!inBag.getMessageParameter(Boolean.class, LoginService.LOGIN_SERVICE.CHECK_LOGIN_METHOD.LOGIN_RESULT))
JSFUtility.addErrorMessage("Login failed!,User name or password is not correct. Try again!", "");

return null;

User user = inBag.getMessageParameter(User.class, LoginService.LOGIN_SERVICE.CHECK_LOGIN_METHOD.LOGIN_USER);

//Fire Event
LoggedInEvent event = new LoggedInEvent(user);

return "adminHome";

return "userHome";

Here, if logged in is succefull, LoggedInEvent event object is fired by the method, "loggedInEvent#fire(event)".  Nice feature of CDI :). Observers specify with event type that would like to observe.

JSF Page

Here is the JSF Facelet page that uses reservation bean instance,

<html xmlns="http://www.w3.org/1999/xhtml"

<title>Sample Web Application</title>
<link type="text/css" rel="stylesheet" href="#{facesContext.externalContext.requestContextPath}/main.css"/>


<ui:composition template="/user/menu.xhtml">

<ui:define name="caption">
<h:outputText value="Add Reservation Page" styleClass="captionTitle" />

<ui:define name="body">

<h:form id="form">


<f:facet name="header">
<h:outputText value="Add New Reservation" />

<h:panelGrid columns="2" styleClass="table" cellspacing="2" cellpadding="5" columnClasses="leftColumns,rightColumns">
<h:outputText value="Reservation Date : " />

<rich:calendar datePattern="dd/MM/yyyy" value="#{userReservationBean.reservationDate}">


<h:dataTable id="dt" cellpadding="5" value="#{userReservationBean.hotels}" binding="#{userReservationBean.model}" var="model" styleClass="table dataTable" rowClasses="oddRow,evenRow">

<h:column id="dt1">
<f:facet name="header">
<h:outputText id="col1" value="Name" />

<h:outputText id="col11" value="#{model.name}" />

<h:column id="dt2">
<f:facet name="header">
<h:outputText id="col2" value="Star" />

<h:outputText id="col22" value="#{model.star}" />

<h:column id="dt5">
<h:commandLink action="#{userReservationBean.addReservation}" value="Add Hotel for Reservation" />



<f:facet name="header">
<h:outputText value="Added Hotels For Reservation" />

<div class="caption">
<h:outputText value="Added Hotels" styleClass="captionTitle" />

<h:panelGrid columns="2" styleClass="table" cellspacing="2" cellpadding="5" columnClasses="leftColumns,rightColumns">

<h:outputLabel for="name">
<h:outputText value="Name" />

<h:selectManyListbox style="width:225px;height:75px;" value="#{userReservationBean.itemSelected}">
<f:selectItems value="#{userReservationBean.reservations}"/>

<h:commandButton action="#{userReservationBean.checkout}" value="Checkout" />

<h:commandButton action="#{userReservationBean.delete}" value="Delete" />
<h:commandButton action="#{userReservationBean.clear}" value="Cancel" />




Model Layer

Model layer only contains JPA entity classes and JPA configuration file. For example, here is the part of the Reservation class,

public class Reservation
private int id;

private User user;

private Hotel hotel;

private Date reservationDate;

private int version;

public Reservation()


 Utility Layer

This layer contains some utility classes that are used by all layers. For example, it contains CDI binding types,constants etc.

 Service Layer

 This layer contains the business services of the application that interacts with database. It uses Defne annotations heavily. Below is the Register Service,

public class RegisterService
private static final ILogger logger = LoggerProvider.getLogProvider(RegisterService.class);

public static Message registerUser(Message inBag) throws DefneException
Message oBag = MessageFactory.newServiceBag(inBag.isReturnsOutMessage());
String userName = inBag.getMessageParameter(String.class, "USER_NAME");
String password = inBag.getMessageParameter(String.class, "PASSWORD");
String name = inBag.getMessageParameter(String.class, "NAME");
String surname = inBag.getMessageParameter(String.class, "SURNAME");
int age = inBag.getMessageParameter(Integer.class, "AGE");
boolean admin = inBag.getMessageParameter(Boolean.class, "ADMIN");

EntityManager entityManager = EntityManagerUtil.getEntityManagerFromBag(inBag);
logger.info("Register a new user with user name : " + userName);

if(GenericValidator.isBlankOrNull(userName) || GenericValidator.isBlankOrNull(password))
logger.info("Registering is failed. User name and password can not be null");
return null;

User user = new User();



oBag.putMessageParameter("USER", user);
catch (Exception e)

return oBag;

 TransactionAttribute and EntityManagerAttribute annotations are used for defining Transaction and JPA requirements of the service operation.

Rich Faces Configuration for JSF 2

To use RichFaces 3.3.3 in JSF 2 environment (like Apache MyFaces 2.0.1 in SIwpas), you have to tweak some parameters in faces-config.xml and web.xml of the application. Here is the necessary part for faces-config.xml,


 And here is the web.xml,







<display-name>RichFaces Filter</display-name>

<servlet-name>Faces Servlet</servlet-name>


<servlet-name>Faces Servlet</servlet-name>

<servlet-name>Faces Servlet</servlet-name>



 To use RichFaces with JSF 2, you have to disable Facelet support in JSF 2 and manually add Facelet libraries to your web application classpath.

beans.xml and defne-service.xml Files

Those files are used by the Apache OpenWebBeans and Defne respectively. defne-service.xml file is a marker file that is put into META-INF/ folder of the application classpath.  Defne framework looks for this file to scan deployment. beans.xml is a CDI configuration file.

JPA persistence.xml File

Defne framework uses Java Persistence API for  handling database operations. Here is the persistence.xml file used by the application that is contained in "Model" layer.

	<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">


<property name="openjpa.jdbc.DBDictionary" value="hsql" />
<property name="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver" />
<property name="openjpa.ConnectionURL" value="jdbc:hsqldb:mem:test" />
<property name="openjpa.ConnectionUserName" value="sa" />
<property name="openjpa.ConnectionPassword" value="" />
<property name="openjpa.Log" value="DefaultLevel=TRACE" />
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />



Source Code Of The Application

Source code of the reservation application can be downloaded from SVN, http://defne.googlecode.com/svn/trunk/defne-samples/reservation/


Defne provides an easy way to write your business logic using Java EE technologies. Defne services could be called by different clients easily such as, Pure AJAX, Standalone Java, Java Servlet, JSF, RESTful Services etc. We will add more clients at the next release, such as JMS, TCP, Web Service etc. 

JBoss RichFaces provides powerful AJAX capable JSF components.

Apache OpenWebBeans/CDI provides dependecy injection support,

Java EE JSF 2 (Apache MyFaces) is a powerful MVC framwork for  developing component based AJAX capable web applications,

Java EE JPA 2 (Apache OpenJPA)  is a specification for accessing, persisting, and managing data between Java objects / classes and a relational database

MechSoft SIWpas provides lightweight Java EE Web profile compatible server environment.

Defne URLs

Web Site : http://code.google.com/p/defne/

SVN Site : http://code.google.com/p/defne/source/browse/

Maven Snapshot : https://oss.sonatype.org/content/repositories/snapshots/org/defne/

Maven : http://repo1.maven.org/maven2/org/defne/

Defne Discussion : http://groups.google.com/group/defnedev

RichFace URL

Web Site : http://jboss.org/richfaces

SIwpas URL

Web Site : http://code.google.com/p/siwpas/

Apache Software Foundation

Web Site : http://apache.org


Gurkan Erdogdu

ASF Member,http://apache.org

PMC Chair, Apache OpenWebBeans

CTO, MechSoft Mechanical and Software Solutions, http://www.mechsoft.com.tr

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}