Develop Java EE applications with JBoss AS 7

In this tutorial we will learn how to create and deploy a Java EE 6 application on JBoss AS 7 using the following technologies:

  • EJB 3.1 Singletons
  • JSF 2.0
  • MySQL as database.


This example application will emulate a simple caching system where data is persisted on a storage DB (MySQL) and queried from an in-memory ArrayList.

The prerequisite to this tutorial is that you have learnt how to install JBossAS Tools on your Eclipse IDE.  
Start by creating a new Dynamic Web Project, selecting as Target Runtime your JBoss AS 7 distribution. Click Finish.


develop application jboss 7
Next, add the single Web page named home.xhtml which will be used to collect data (css style sheets not included for brevity):

<!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"
    xmlns:c="http://java.sun.com/jsp/jstl/core">

<h:body>
    <h2>JSF 2 example on JBoss 7</h2>
    <h:form id="jsfexample">
        <h:panelGrid columns="2" styleClass="default">

            <h:outputText value="Enter key:" />
            <h:inputText value="#{manager.key}" />

            <h:outputText value="Enter value:" />
            <h:inputText value="#{manager.value}" />

            <h:commandButton actionListener="#{manager.save}"
                styleClass="buttons" value="Save key/value" />
            <h:commandButton actionListener="#{manager.clear}"
                styleClass="buttons" value="Clear cache" />

            <h:messages />


        </h:panelGrid>


        <h:dataTable value="#{manager.cacheList}" var="item"
            styleClass="table" headerClass="table-header"
            rowClasses="table-odd-row,table-even-row">
            <h:column>
                <f:facet name="header">Key</f:facet>
                <h:outputText value="#{item.key}" />
            </h:column>
            <h:column>
                <f:facet name="header">Value</f:facet>
                <h:outputText value="#{item.value}" />
            </h:column>
        </h:dataTable>
    </h:form>
</h:body>
</html>


As you can see, basically this Web page uses the manager.key and manager.value to store the single keys to be stored. The JSF actions are triggered by manager.save and manager.clear. Next, in the lower part of the page, a dataTable is included to show in tabular form the entries which are recovered via the manager.cacheList object.

Now let's add the manager JSF Bean which acts as a layer between the Web page and the EJB:

package com.sample.bean;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import com.sample.ejb.SingletonBean;

@ManagedBean(name="manager")
public class PropertyManager {
  
    @EJB
    SingletonBean ejb;

    ArrayList  cacheList  = new ArrayList ();

    private String key;
    private String value;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public void save() {
        ejb.put(key, value);
    }

    public void clear() {
        ejb.delete();

    }
    public List getCacheList() {
        return ejb.getCache();
    }


}


As you can see from the annotation @ManagedBean(name="manager"), since JSF 2.0 you can register your Managed Beans via annotations, this means that is not necessary anymore to use the faces-config.xml to define your beans.
Inside this class, a reference of the Singleton EJB is injected, using the @EJB annotation. If you want to learn more abut Singleton EJB check here:

Fine, now we will code our EJB Singleton which will store data into the MySQL database and recover info from the in-memory cache:

package com.sample.ejb;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.sample.model.Property;

@Singleton

public class  SingletonBean   {

    private  List<Property> cache; 
    @PersistenceContext(unitName = "persistenceUnit")
    private EntityManager em;

    @PostConstruct
    public void initCache(){
        this.cache = queryCache();
        if (cache == null) cache = new ArrayList<Property>();
    }

    public void delete(){

        this.cache.clear();
    }
    public void put(String key,String value){
        Property p = new Property();
        p.setKey(key);
        p.setValue(value);
            em.persist(p);
          
            this.cache.add(p);
    }
    public List<Property> getCache() {
        return cache;
    }
    public List<Property>  queryCache(){
        Query query = em.createQuery("FROM com.sample.bean.Property");

        List <Property> list =  query.getResultList();
        return list;          
    }



}


The EntityManager is created by the EntitiyManagerFactory which is configured by the persistence unit. The persistence unit is described via the file "persistence.xml" in the directory META-INF in the source folder. A set of entities which are logical connected will be grouped via a persistence unit. "persistence.xml" defines the connection data to the database, e.g. the driver, the user and the password,

The other parts of this EJB is a pretty simple JPA query (queryCache) which kicks in at start-up. On the other hand data will be stored both in the DB and in-memory using the put method.

Let's move to the Persistence Unit definition file, persistence.xml which needs to be placed into the src/META-INF path of your Eclipse project:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="persistenceUnit" transaction-type="JTA">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
            <jta-data-source>java:jboss/datasources/MySqlDB</jta-data-source>  
              
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
        </properties>
    </persistence-unit>
</persistence>


In order to run this example, it requires a DataSource which is bound into the JNDI context named "java:jboss/datasources/MySqlDB".
Check here how to deploy a Datasource on JBoss AS 7.    http://www.mastertheboss.com/jboss-application-server/375-jboss-as-7-deployable-datasources.html

Last piece of the puzzle is the Property Entity class which maps the Property database table, using as @Id the key variable:
package com.sample.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Property {

    @Id 
    @Column(name="id")
    private String key;

    private String value;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }


}


You are almost done, create quickly your Table on your MySQL Db and get started:
mysql> create table property (
    -> id varchar(100),
    -> value varchar(100)
    -> );

Fine, your project is completed and should look like this in your Project Explorer window:
develop application jboss 7
Let's test is using: http://localhost:8080/as7sample/home.xhtml
develop application jboss 7
Test the application by adding keys using the Save key/value button.

 

The source code for this tutorial is available here: https://github.com/fmarchioni/mastertheboss/tree/master/javaee/javaee6example

Java EE 7 users ?

An updated Project has been added on github at: https://github.com/fmarchioni/mastertheboss/tree/master/javaee/javaee7example . This example is designed to run on WildFly 10 using Java EE 7 dependencies

Done we have completed our tutorial. Now continue reading here, and you will learn how to create a more advanced application using Apache Maven's Java EE 6 archetype application.

Related articles available on mastertheboss.com

JBoss AS 7 introduction

This is an introduction tutorial to the newest JBoss AS 7 which a

Adding users with JBoss AS 7

If you are planning to add new users to your management interface

Using JBoss AS 7 management API programmatically

In this tutorial we will show how to use detyped management API t

JNDI view in JBoss AS 7

JNDI can be checked on the naming subsystem of the application se

How to install a module on WildFly / JBoss AS 7

Installing a module on WildFly / JBoss AS 7 requires creating a p

JBoss AS 7 classloading

JBoss AS 7 classloading explained As mandated by Java EE specifi

Follow us on Twitter