This entry is a follow up to TOTD #95 and shows how to use the recent integrations of JSR 299 in GlassFish v3 to convert a JSF managed bean to a JSR 299 bean (aka Web Beans). The TOTD #95 describes a simple Java EE 6 web application that uses Java Server Faces 2.0 components for displaying the results of a database query conducted by EJB 3.1 and JPA 2.0 classes.
The EJB class, which also acts as the JSF managed bean, looks like:
@javax.ejb.Stateless
@ManagedBean
public class StateList {
@PersistenceUnit
EntityManagerFactory emf;
public List getStates() {
return emf.createEntityManager().createNamedQuery(”States.findAll”).getResultList();
}
}
Three changes are required to convert this class into a JSR 299 compliant bean (Web Bean) as listed below:
- Add an empty "beans.xml" to the WEB-INF directory.
- Replace "@ManagedBean" with "@javax.inject.Named annotation". "@javax.inject" annotations are defined by JSR 330.
- Resource injection does not work with JPA classes, yet, so populate EntityManager explicitly as explained below:
- Replace EntityManagerFactory resource injection:
@PersistenceUnit EntityManagerFactory emf;
with:
EntityManager emf = Persistence.createEntityManagerFactory("HelloEclipseLinkPU");
- Add the required entity classes explicitly to "persistence.xml". If the persistence unit is injected then the container automatically scans the web application root for any entity classes.
- Expand "Configuration Files" and edit "persistence.xml".
- Uncheck "Include All Entity Classes in …" check box.
- Click on "Add Class…", select "state.States", and click on "OK".
- Replace EntityManagerFactory resource injection:
That’s it, re-deploy your application and now you are using the Web Beans integration in GlassFish v3 instead of JSF managed bean. The output is available at "http://localhost:8080/HelloEclipseLink/forwardToJSF.jsp" as shown:
This is the exact same output as shown in TOTD #95.
Now, one-by-one, JPA, EJB, Transactions and other components will start working. Read Roger’s blog for another example of Web Beans in GlassFish.
A complete archive of all the tips is available here.
Technorati: totd glassfish v3 mysql javaee6 javaserverfaces webbeans jsr299 netbeans
Related posts:- TOTD #129: Managed Beans 1.0 in Java EE 6 – What and How ?
- TOTD #123: f:ajax, Bean Validation for JSF, CDI for JSF and JPA 2.0 Criteria API – all in one Java EE 6 sample application
- TOTD #108: Java EE 6 web application (JSF 2.0 + JPA 2.0 + EJB 3.1) using Oracle, NetBeans, and GlassFish
- TOTD #144: CDI @Produces for container-managed @Resource
- TOTD #134: Interceptors 1.1 in Java EE 6 – What and How ?