DocsSimpleJSF2EJB31

Getting Started with Java EE 6 Applications

This document provides a brief introduction to some of the features introduced as part of Java EE 6 specification. In this tutorial you will create a simple Java EE 6 web application that contains an EJB 3.1 stateless session bean. The generated session bean uses queries that are defined in the Criteria API that is part of JPA 2.0. You will then create a named managed bean that accesses the session facade and a presentation layer that uses the Facelets view framework as specified in JSF 2.0.

The Enterprise JavaBean (EJB) 3.1 specification that is part of the Java EE 6 specification is designed to simplify creating and using EJBs. The EJB 3.1 architecture enables you to create session beans without the business interfaces that were required in EJB 3.0. You can now also package EJB components directly in a WAR archive. This eliminates the need to create separate EJB modules that are packaged as a JAR archive in an EAR archive.

The JavaServer Faces (JSF) 2.0 specification adds Facelets as a view technology. This means that managed beans can now be annotated directly in the source code with @ManagedBean instead of requiring entries in the faces-config.xml file. For more about support in the IDE for the JavaServer Faces 2.0 specification, see JSF 2.0 Support in NetBeans IDE 6.8.


This tutorial is based on the blog post Simplest Possible JSF 2 / EJB 3.1 / JPA Component - With WAR Deployment by Adam Bien. You can find additional Java EE examples at Adam Bien's Kenai project Java EE Patterns and Best Practices and in his book "Real World Java EE Patterns - Rethinking Best Practices", available at http://press.adam-bien.com.

Contents


Requirements for This tutorial

You need the following software:

  • NetBeans IDE 6.8 Beta
  • GlassFish v3 (including the bundled JavaDB database)


Create Web Application

In this exercise you create a simple web application. When you create the web application you will specify the bundled GlassFish v3 application server as the target Java EE container. The GlassFish v3 application server is Java EE compatible and includes the JSF 2.0 libraries that are required in this application.

In the New Project wizard you will also choose Java EE 6 Web as the Java Source level. Java EE 6 Web is a lightweight Java EE 6 profile that contains a subset of the full Java EE 6 platform. Java EE 6 Web is designed for web applications that do not require the full set of Java EE 6 technologies. The Web profile supports the transaction processing and persistence management that are commonly used in smaller enterprise web applications. You can use the Java EE Web profile for web applications that use session beans with a local interface or no interface. The full Java EE profile is required if the application uses a remote interface.

You will also specify the JavaServer Faces framework in the wizard.

To create the web application:

  1. Choose File > New Project (Ctrl-Shift-N). Select Web from the Java Web category and click Next.
  2. Type SimpleEE6App for the project name and set the project location.
  3. Select GlassFish v3 and Java EE 6 Web. Click Next.
    \ New Project Wizard
    \
  4. Select JavaServer Faces. Click Finish.
    \ By default, the IDE will select Facelets as the view technology. If you do not want to use Facelets, you can choose JSP as the preferred page languagae in the Configuration tab of the Frameworks pane.
    \


File:Newproject-frameworks DocsSimpleJSF2EJB31.png Frameworks panel in New Project Wizard

When you click Finish, the IDE creates the project and opens the project in the Projects window. The IDE automatically creates the JSF pages index.xhtml and template.xhtml and opens index.xhtml in the editor. If you open web.xml, you can see that Facelets is defined as the view framework and that index.xhtml is specified as the welcome page for the application.


Create the HelloMessage Entity Class

In this exercise you will create a simple persistent entity class. Support for using a plain old java object (POJO) as a persistent object was introduced in the Java EE 5 specification. You will add one field and generate a getter and setter for the new field.

To create the entity class:

  1. Right-click the project node and choose New > Other
  2. Select Entity Class from the Persistence category. Click Next.
  3. Type HelloMessage for the Class Name.
  4. Type entities for the Package.
  5. Click Create Persistence Unit.
    \File:Persistence-unit DocsSimpleJSF2EJB31.png New Persistence Unit
    \
  6. Select jdbc/sample as the datasource. Keep the other defaults (PU name, EclipseLink). Click Create.
  7. Click Finish.
  8. In the editor, add the following field and create getters and setters for the field by typing Ctrl-I and choosing getters and setters in the Insert Code dialog box.
private String message;

Save your changes.

When you run the application, a database table for HelloMessage will be automatically created. A column for the message field will also be created.


Create the Session Bean

In this exercise you will use a wizard to create a stateless session facade for the HelloMessage entity.

One of the major improvements in Java EE 6 is simplifying the EJB specification. The EJB 3.1 specification makes it possible to package EJBs in web applications. Another feature of the EJB 3.1 specification is that business interfaces for session beans are now optional. When the client accessing the bean is a local client, you can choose to use a no-interface view to expose the bean.

To create the session bean:

  1. Right-click the project node and choose New > Other
  2. Select Session Bean for Entity Class from the Persistence category. Click Next.
  3. Select the HelloMessage entity and click Add. Click Next.
  4. Type beans for the package. Click Finish.

Notice that you do not choose to create a business interface for the session bean. Instead, the bean is exposed to the local managed bean using a no-interface view.

File:Session-beans-entity DocsSimpleJSF2EJB31.png New Session Bean for Entity Class Wizard

When you click Finish, the IDE creates HelloMessageFacade.java and opens the class in the editor. The @Stateless annotation marks the class as a stateless session bean. The bean contains the business logic and manages the EntityManager.

When you created the facade for the entity using the wizard, the IDE automatically added the @PersistenceContext annotation to inject the entity manager. By default, the IDE generates methods to create, edit, remove and find entities. The EntityManager API defines the methods that are used to interact with the persistence context, and responsibility for managing the lifecycle of entities in the persistence context is assigned to the container. This results in less code because the entity lifecycle is managed by the container and not by the application.

@Stateless
public class HelloMessageFacade {
    @PersistenceContext(unitName = "SimpleEE6AppPU")
    private EntityManager em;

The IDE also generated some commonly used default methods that use methods defined in the Criteria API for creating queries. The Criteria API is part of JPA 2.0 which was introduced as part of the Java EE 6 specification.

public List<HelloMessage> findAll() {
    CriteriaQuery cq = em.getQueryBuilder().createQuery();
    cq.select(cq.from(HelloMessage.class));
    return em.createQuery(cq).getResultList();
}

public List<HelloMessage> findRange(int[] range) {
    CriteriaQuery cq = em.getQueryBuilder().createQuery();
    cq.select(cq.from(HelloMessage.class));
    Query q = em.createQuery(cq);
    q.setMaxResults(range[[1 | 1]] - range[0]);
    q.setFirstResult(range[0]);
    return q.getResultList();
}

public int count() {
    return ((Long) em.createQuery("select count(o) from HelloMessage as o").getSingleResult()).intValue();
}


Create the Managed Bean

In this exercise you will create a simple JSF managed bean that is used to access the session facade.

The JSF 2.0 specification that is part of Java EE 6 enables you to use annotations in the bean class. This means that you can identify a class as a JSF managed bean using the @ManagedBean annotation and you no longer need to specify JSF managed beans in the faces-config.xml file. You can also use annotations to specify the scope.

For more about support in the IDE for the JavaServer Faces 2.0 specification, see JSF 2.0 Support in NetBeans IDE 6.8.

To create the managed bean:

  1. Right-click the project node and choose New > Other
  2. Select JSF Managed Bean from the JavaServer Faces category. Click Next.
  3. Type MessageView for the Class Name.
  4. Type my.presentation for the Package
  5. Type messageview for name.
  6. Set Scope to Request. Click Finish.

You will use the Managed Bean name messageview as the value for the inputText and commandButton in the JSF page index.xhtml when calling methods in the bean. When you create the managed bean using the wizard, you can leave the Name field empty and the IDE will by default assign a name to the bean based on the name of the bean class.

New JSF Managed Bean

In the Projects window you will see the following files.

File:Projects-window DocsSimpleJSF2EJB31.png Projects window

When you click Finish, the IDE creates the bean class and opens the class in the editor. You can see that the IDE added the @ManagedBean and @RequestScoped annotations and the name of the bean.

@ManagedBean(name="messageview")
@RequestScoped
public class MessageView {

You will now use dependency injection to obtain a reference to the HelloMessageFacade session bean and add some simple methods to get the number of messages. The IDE's code completion can help you when typing the methods.

Add the following code to the class.

public class MessageView {

    // Injects the HelloMessageFacade session bean using the @EJB annotation
    @EJB
    HelloMessageFacade helloMessageFacade;

    // Creates a new field
    private HelloMessage message;


    // Creates a new instance of HelloMessage 
    public MessageView() {
       this.message = new HelloMessage();
    }

    // Calls getMessage to retrieve the message
    public HelloMessage getMessage() {
       return message;
    }

    // Returns the total number of messages
    public int getNumberOfMessages(){
       return helloMessageFacade.findAll().size();
    }

    // Saves the message and then returns the string "theend"
    public String save(){
       this.helloMessageFacade.create(message);
       return "theend";
    }
}

Save your changes and fix your imports.

Notice that the save method returns the string "theend". The JSF 2.0 specification enables the use of implicit navigation rules in Facelets applications. In this application, no navigation rules are configured in faces-config.xml. Instead, the navigation handler will try to locate a suitable page in the application. In this case, the navigation handler will try to locate a page named theend.xhtml when the save method is invoked.


Modify the index.xhtml page

In this exercise you will make some simple changes to the index.xhtml page to add some UI components. You will add a form with an input text field and a button.

  1. Open index.xhtml in the editor.
  2. Add the following simple form between the <ui:define> tags
<ui:define name="body">
       <h:form>
            <h:outputLabel value="Message:"/><h:inputText value="#{messageview.message.message}"/>
            <h:commandButton action="#{messageview.save}" value="Save"/>
       </h:form>
</ui:define>

Save your changes.

You can see that inputText and commandButton will invoke the methods in the named JSF managed bean messageview. The save method will return "theend", and the navigation handler will look for a page named theend.xhtml.

Create the page to display results

In this exercise you will create the page theend.xhtml that will display the results.

  1. Right-click the project node and choose New > Other.
  2. Select JSF Page from the JavaServer Faces category. Click Next.
  3. Type theend as the File Name.
  4. Make sure that the Facelets option is selected. Click Finish.
  5. Type the following elements between the <body> tags in theend.xhtml.
<body>
<h:outputLabel value="Thanks! There are "/> <h:outputText value="#{messageview.numberOfMessages}"/> messages!
</body>

Save your changes.

Notice that when you start adding the JSF UI elements, the IDE automatically adds the xmlns:h="http://java.sun.com/jsf/html tag library definition to the file.


Running the application

You are now finished coding the application. You can now run the application in your browser.

  1. Right-click the project node and choose Run from the popup menu to deploy the application and open index.xhtml in your browser.
  2. Type a message in the text field. Click Save.

File:Browser1 DocsSimpleJSF2EJB31.png Facelets welcome page in browser

When you click Save, the message is saved to the database and the number of messages is retrieved and displayed in theend.xhtml.

File:Browser2 DocsSimpleJSF2EJB31.png Page displaying results

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo