Before mixing JSF and EJB (JPA based) let's have a brief description of these two notions:
Now, JSF, EJB, and JPA can be mixed to provide a powerful web application. Let's see how to accomplish this!
For testing this solution we have used (and recommend) GlassFish v3, as an application server, and NetBeans 6.8 as an IDE (you will see in There's more section, why we prefer NetBeans version 6.8).
We jump right into example, and we consider the following JSF view fragment (a simple login form):
… <h:form> <h:outputLabel value="Name:"/> <h:inputText value="#{bean.name}"/> <h:outputLabel value="Password:"/> <h:inputText value="#{bean.password}"/> <h:commandButton action="#{bean.login}" value="Login"/> </h:form> …
Now, the managed bean that is behind our form is defined as follows:
@ManagedBean(name="bean") @RequestScoped public class Bean { @EJB LoginService loginService; private String name; private String password; //place here getter and setter for 'name' and 'password' properties public String login(){ String loginSuccess = this.loginService.loginUser (username, userpassword); return //return a corresponding message depending on loginSuccess } }
So far you saw the JSF part of our application, and we have injected a stateless session bean in our managed bean. The next step is to write our entity bean that maps name
and password
to a database:
@Entity @Table(name = "userstable") public class Users implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private String username; private String userpassword; //getter and setter methods for 'username' and 'userpassword' properties }
Next we build the stateless session bean, LoginService
, which makes use of JPA to access the database and implement login business logic:
@Stateless @LocalBean public class MapycAccountsBean { @PersistenceContext(unitName = "mapyc-ejbPU") private EntityManager em; public String loginUser(String username, String userpassword){ //use 'em' to query and login user //return a message code depending on login success } }
Done!
The key to it is that the JSF managed bean supports session bean injection. Be careful to avoid injecting stateful session beans in "stateless" managed beans, for example in a managed bean placed on request scope.
You can use JSF 2.0 without EJBs, but then you will have to manage the persistence and transactions manually. When you don't want to deal with this task, it is recommended to use EJB or something similar.
Starting with NetBeans 6.8 we can generate a JSF 2.0 application from an existing database using EJB 3.1 and JPA 2. You can apply the wizard to a Java EE 6 project and deploy it to Glassfish v3. Here are the steps:
persistence.xml
file.The generated code can be customized later to satisfy you project's needs.