





















































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.
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:
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:
The web tier of the application is build using the JavaServer Faces technology, while EJB is used to implement the database-related code.
To build the sample discussed here, you will need the following software components installed on your computer:
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.
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:
Setting | Value |
Name | jdbc/mysqlPool |
Resource type | javax.sql.DataSource |
Database Vendor | mysql |
Name | Value |
databaseName | my_db |
serverName | localhost |
port | 3306 |
user | usr |
password | pswd |
The next step is to create an application project with NetBeans. To do this, follow the steps below:
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.
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:
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.
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:
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.
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:
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
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:
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.
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:
<%@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.
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.
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.