15 min read

Building JSF/EJB3 Applications

This practical article shows you how to create a simple data-driven application using JSF and EJB3 technologies. The article also shows you how to effectively use NetBeans IDE when building enterprise applications.

What We Are Going to Build

The sample application we are building throughout the article is very straightforward. It offers just a few pages. When you click the Ask us a question link on the welcomeJSF.jsp page, you will be taken to the following page, on which you can submit a question:

 

Building JSF/EJB3 Applications

 

Once you’re done with your question, you click the Submit button. As a result, the application persist your question along with your email in the database. The next page will look like this:

 

Building JSF/EJB3 Applications

 

The web tier of the application is build using the JavaServer Faces technology, while EJB is used to implement the database-related code.

Software You Need to Follow the Article Exercise

To build the sample discussed here, you will need the following software components installed on your computer:

  • Java Standard Development Kit (JDK) 5.0 or higher
  • Sun Java System Application Server Platform Edition 9
  • MySQL
  • NetBeans IDE 5.5

Setting Up the Database

The first step in building our application is to set up the database to interact with. In fact, you could choose any database you like to be the application’s backend database. For the purpose of this article, though, we will discuss how to use MySQL.

To keep things simple, let’s create a questions table that contains just three columns, outlined in the following table:

Column Type Description
trackno INTEGER AUTO_INCREMENT PRIMARY KEY Stores a track number generated automatically when a row is inserted.
user_email VARCHAR(50) NOT NULL  
question VARCHAR(2000) NOT NULL  

Of course, a real-world questions table would contain a few more columns, for example, dateOfSubmission containing the date and time of submitting the question. To create the questions table, you first have to create a database and grant the required privileges to the user with which you are going to connect to that database. For example, you might create database my_db and user usr identified by password pswd. To do this, you should issue the following SQL commands from MySQL Command Line Client:

 

CREATE DATABASE my_db;

GRANT CREATE, DROP, SELECT, INSERT, UPDATE, DELETE
ON my_db.*
TO ‘usr’@’localhost’
IDENTIFIED BY ‘pswd’;

In order to use the newly created database for subsequent statements, you should issue the following statement:

 

USE my_db

 

Finally, create the questions table in the database as follows:

 

CREATE TABLE questions(
     trackno INTEGER AUTO_INCREMENT PRIMARY KEY,
     user_email VARCHAR(50) NOT NULL,
     question  VARCHAR(2000) NOT NULL
) ENGINE = InnoDB;

 

 

Once you’re done, you have the database with the questions table required to store incoming users’ questions.

Setting Up a Data Source for Your MySQL Database

Since the application we are going to build will interact with MySQL, you need to have installed an appropriate MySQL driver on your application server. For example, you might want to install MySQL Connector/J, which is the official JDBC driver for MySQL. You can pick up this software from the “downloads” page of the MySQL AB website at http://mysql.org/downloads/. Install the driver on your GlassFish application server as follows:

  • Unpack the downloaded archive containing the driver to any directory on your machine
  • Add mysql-connector-java-xxx-bin.jar to the CLASSPATH environment variable
  • Make sure that your GlassFish application server is up and running
  • Launch the Application Server Admin Console by pointing your browser at http://localhost:4848/
  • Within the Common Tasks frame, find and double-click the ResourcesJDBCNew Connection Pool node
  • On the New Connection Pool page, click the New… button
  • The first step of the New Connection Pool master, set the fields as shown in the following table:
Setting Value
Name jdbc/mysqlPool
Resource type javax.sql.DataSource
Database Vendor mysql

 

  • Click Next to move on to the second page of the master
  • On the second page of New Connection Pool, set the properties to reflect your database settings, like that shown in the following table:
Name Value
databaseName my_db
serverName localhost
port 3306
user usr
password pswd

 

  • Once you are done with setting the properties, click Finish. The newly created jdbc/mysqlPool connection pool should appear on the list. To check it, you should click its link to open it in a window, and then click the Ping button. If everything is okay, you should see a message telling you Ping succeeded

Creating the Project

The next step is to create an application project with NetBeans. To do this, follow the steps below:

  • Choose File/New project and then choose the EnterpriseEnterprise Application template for the project. Click Next
  • On the Name and Location page of the master, specify the name for the project: JSF_EJB_App. Also make sure that Create EJB Module and Create Web Application Module are checked. And click Finish

As a result, NetBeans generates a new enterprise application in a standard project, containing actually two projects: an EJB module project and Web application project. In this particular example, you will use the first project for EJBs and the second one for JSF pages.

Creating Entity Beans and Persistent Unit

You create entity beans and the persistent unit in the EJB module project—in this example this is the JSF_EJB_App-ejb project. In fact, the sample discussed here will contain the only entity bean: Question. You might automatically generate it and then edit as needed. To generate it with NetBeans, follow the steps below:

  • Make sure that your Sun Java System Application Server is up and running
  • In the Project window, right click JSF_EJB_App-ejb project, and then choose New/Entity Classes From Database. As a result, you’ll be prompted to connect to your Sun Java System Application Server. Do it by entering appropriate credentials.
  • In the New Entity Classes from Database window, select jdbc/mysqlPool from the Data Source combobox. If you recall from the Setting up a Data Source for your MySQL database section discussed earlier in this article, jdbc/mysqlPool is a JDBC connection pool created on your application server
  • In the Connect dialog appeared, you’ll be prompted to connect to your MySQL database. Enter password pswd, set the Remember password during this session checkbox, and then click OK
  • In the Available Tables listbox, choose questions, and click Add button to move it to the Selected Tables listbox. After that, click Next
  • On the next page of the New Entity Classes from Database master, fill up the Package field. For example, you might choose the following name: myappejb.entities. And change the class name from Questions to Question in the Class Names box. Next, click the Create Persistent Unit button
  • In the Create Persistent Unit window, just click the Create button, leaving default values of the fields
  • In the New Entity Classes from Database dialog, click Finish

As a result, NetBeans will generate the Question entity class, which you should edit so that the resultant class looks like the following:

 

package myappejb.entities;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = “questions”)
public class Question implements Serializable {

@Id
@Column(name = “trackno”)
private Integer trackno;

@Column(name = “user_email”, nullable = false)
private String userEmail;

@Column(name = “question”, nullable = false)
private String question;

public Question() {
}

public Integer getTrackno() {
return this.trackno;
}
public void setTrackno(Integer trackno) {
this.trackno = trackno;
}
public String getUserEmail() {
return this.userEmail;
}

public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}

public String getQuestion() {
return this.question;
}

public void setQuestion(String question) {
this.question = question;
}

}

 

 

Once you’re done, make sure to save all the changes made by choosing File/Save All.

Having the above code in hand, you might of course do without first generating the Question entity from the database, but simply create an empty Java file in the myappejb.entities package, and then insert the above code there. Then you could separately create the persistent unit. However, the idea behind building the Question entity with the master here is to show how you can quickly get a required piece of code to be then edited as needed, rather than creating it from scratch.

Creating Session Beans

To finish with the JSF_EJB_App-ejb project, let’s proceed to creating the session bean that will be used by the web tier. In particular, you need to create the QuestionSessionBean session bean that will be responsible for persisting the data a user enters on the askquestion page. To generate the bean’s frame with a master, follow the steps below:

  • In the Project window, right click JSF_EJB_App-ejb project, and then choose New/Session Bean
  • In the New Session Bean window, enter EJB name: QuestionSessionBean. Then specify the package: myappejb.ejb. Make sure that the Session Type is set to Stateless and Create Interface is set to Remote. Click Finish

As a result, NetBeans should generate two Java files: QuestionSessionBean.java and QuestionSessionRemote.java. You should modify QuestionSessionBean.java so that it contains the following code:

 

package myappejb.ejb;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;
import myappejb.entities.Question;

@Stateless
<b>@TransactionManagement(TransactionManagementType.BEAN)</b>
public class QuestionSessionBean implements myappejb.ejb.QuestionSessionRemote {

/** Creates a new instance of QuestionSessionBean */
public QuestionSessionBean() {
}
@Resource
private UserTransaction utx;

@PersistenceUnit(unitName = “JSF_EJB_App-ejbPU”)
private EntityManagerFactory emf;

private EntityManager getEntityManager() {
return emf.createEntityManager();
}

public void save(Question question) throws Exception {
EntityManager em = getEntityManager();
try {
utx.begin();
em.joinTransaction();
em.persist(question);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
throw new Exception(ex.getLocalizedMessage());
} catch (Exception e) {
throw new Exception(e.getLocalizedMessage());
}
} finally {
em.close();
}
}
}

 

Next, modify the QuestionSessionRemote.java so that it looks like this:

 

package myappejb.ejb;

import javax.ejb.Remote;
import myappejb.entities.Question;

@Remote
public interface QuestionSessionRemote {
void save(Question question) throws Exception;

}

 

Choose File/Save All to save the changes made. That’s it. You just finished with your EJB module project.

Adding JSF Framework to the Project

Now that you have the entity and session beans created, let’s switch to the JSF_EJB_App-war project, where you’re building the web tier for the application.Before you can proceed to building JSF pages, you need to add the JavaServer Faces framework to the JSF_EJB_App-war project. To do this, follow the steps below:

  • In the Project window, right click JSF_EJB_App-war project, and then choose Properties
  • In the Project Properties window, select Frameworks from Categories, and click Add button. As a result, the Add a Framework dialog should appear
  • In the Add a Framework dialog, choose JavaServer Faces and click OK Then click OK in the Project Properties dialog

As a result, NetBeans adds the JavaServer Faces framework to the JSF_EJB_App-war project. Now if you extend the Configuration Files folder under the JSF_EJB_App-war project node in the Project window, you should see, among other configuration files, faces-config.xml there. Also notice
the appearance of the welcomeJSF.jsp page in the Web Pages folder


Creating JSF Managed Beans

The next step is to create managed beans whose methods will be called from within the JSF pages. In this particular example, you need to create only one such bean: let’s call it QuestionController. This can be achieved by following the steps below:

  • In the Project window, right click JSF_EJB_App-war project, and then choose New/Empty Java File
  • In the New Empty Java File window, enter QuestionController as the class name and enter myappjsf.jsf in the Package field. Then, click Finish
  • In the generated empty java file, insert the following code:

 

package myappjsf.jsf;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import myappejb.entities.Question;
import myappejb.ejb.QuestionSessionBean;

public class QuestionController {
@EJB
private QuestionSessionBean sbean;
private Question question;

public QuestionController() {
}
public Question getQuestion() {
return question;
}

public void setQuestion(Question question) {
this.question = question;
}
public String createSetup() {
this.question = new Question();
this.question.setTrackno(null);
return “question_create”;
}
public String create() {
try {
Integer trck = sbean.save(question);
addSuccessMessage(“Your question was successfully submitted.”);
}
catch (Exception ex) {
addErrorMessage(ex.getLocalizedMessage());
}
return “created”;
}
public static void addErrorMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, facesMsg);
}

public static void addSuccessMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(“successInfo”, facesMsg);
}
}

 

Next, you need to add information about the newly created JSF managed bean to the faces-config.xml configuration file automatically generated when adding the JSF framework to the project. Find this file in the following folder: JSF_EJB_App-warWeb PagesWEB-INF in the Project window, and then insert the following tag between the and tags:

 

  <managed-bean>
    <managed-bean-name>questionJSFBean</managed-bean-name>
    <managed-bean-class>myappjsf.jsf.QuestionController</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
  </managed-bean>

 

Finally, make sure to choose File/Save All to save the changes made in faces-config.xml as well as in QuestionController.java.

Creating JSF Pages

To keep things simple, you create just one more JSF page: askquestion.jsp, where a user can submit a question. First, though, let’s modify the welcomeJSF.jsp page so that you can use it to move on to askquestion.jsp and then return to, once a question has been submitted. To achieve this, modify welcomeJSF.jsp as follows:

 

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<%@taglib prefix=”f” uri=”http://java.sun.com/jsf/core”%>
<%@taglib prefix=”h” uri=”http://java.sun.com/jsf/html”%>

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page</title>
</head>
<body>
<f:view>
<h:messages errorStyle=”color: red” infoStyle=”color: green”
layout=”table”/>

<h:form>
<h1><h:outputText value=”Ask us a question” /></h1>
<h:commandLink action=”#{questionJSFBean.createSetup}”
value=”New question”/>

<br>
</h:form>
</f:view>
</body>
</html>

Now you can move on and create askquestion.jsp. To do this, follow the steps below:

  • In the Project window, right click JSF_EJB_App-war project, and then choose New/JSP
  • In the New JSP File window, enter askquestion as the name for the page, and click Finish
  • Modify the newly created askquestion.jsp so that it finally looks like this:

 

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>New Question</title>
    </head>
    <body>
        <f:view>
            <h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>
            <h1>Your question, please!</h1>
            <h:form>
                <h:panelGrid columns="2">
                    <h:outputText value="Your Email:"/>
                    <h:inputText id="userEmail" value=
                    "#{questionJSFBean.question.userEmail}"
                    title="Your Email" />
                    <h:outputText value="Your Question:"/>
                    <h:inputTextarea id="question" value=
                    "#{questionJSFBean.question.question}"
                    title="Your Question" rows ="5" cols="35" />
                </h:panelGrid>
                <h:commandLink action="#{questionJSFBean.create}" value="Create"/>
                <br>
                <a href="/JSF_EJB_App-war/index.jsp">Back to index</a>
            </h:form>
        </f:view>
    </body>
</html>

 

The next step is to set page navigation. Turning back to the faces-config.xml configuration file, insert the following code there.

 

  <navigation-rule>
    <navigation-case>
      <from-outcome>question_create</from-outcome>
      <to-view-id>/askquestion.jsp</to-view-id>
    </navigation-case>
  </navigation-rule>
        <navigation-rule>
    <navigation-case>
      <from-outcome>created</from-outcome>
      <to-view-id>/welcomeJSF.jsp</to-view-id>
    </navigation-case>
  </navigation-rule>

Make sure that the above tags are within the <faces-config> and </faces-config> root tags.

Check It

You are ready now to check the application you just created. To do this, right-click JSF_EJB_App-ejb project in the Project window and choose Deploy Project. After the JSF_EJB_App-ejb project is successfully deployed, right click the JSF_EJB_App-war project and choose Run Project.
As a result, the newly created application will run in a browser. As mentioned earlier, the application contains very few pages, actually three ones. For testing purposes, you can submit a question, and then check the questions database table to make sure that everything went as planned.

Summary

Both JSF and EJB 3 are popular technologies when it comes to building enterprise applications. This simple example illustrates how you can use these technologies together in a complementary way.

LEAVE A REPLY

Please enter your comment!
Please enter your name here