corner imagecorner image
IDEPlatformPluginsDocs & SupportCommunityPartners

Creating an Enterprise Application Using Maven

This tutorial demonstrates how to create a simple enterprise application using NetBeans IDE and Maven archetypes. The tutorial also provides some explanations and tips on using the IDE to create and build Maven applications.

In this tutorial you create an enterprise application that is packaged as an EAR archive and deployed to GlassFish Server Open Source Edition 3. You create the application using the Maven Enterprise Application archetype in the New Project wizard. The application contains an EJB project that contains a persistent entity class, a message-driven bean and a session bean facade for the entity. The application also contains a web project that contains two servlets.

Tutorial Exercises

Content on this page applies to NetBeans IDE 6.8 and 6.9

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required
NetBeans IDE 6.8, 6.9, Java version
Java Development Kit (JDK) version 6
GlassFish Server Open Source Edition 3.0.1

Note. NetBeans IDE 6.9 and the GlassFish server 3.0.1 require Java Development Kit (JDK) 6.

Prerequisites

This document assumes you have some basic knowledge of, or programming experience with, the following technologies:

  • Java Programming
  • NetBeans IDE

Before starting this tutorial you may want to familiarize yourself with the following documentation.

You can download a zip archive of the finished project.

Using Maven in the IDE

Support for Maven is fully integrated in NetBeans IDE. Developing a project that uses the Maven framework is nearly identical to developing a project in Ant. However, there are some differences that are related to the way Maven builds projects and works with dependencies. The following tips can help you avoid some problems if you are creating a Maven application for the first time.

Check your Maven settings

Before creating your first Maven project, it is a good idea to make sure that the IDE is correctly configured to use your local Maven installation and local Maven repository. You should not use the embedded Maven snapshot to develop your project.

  1. Open the Options window in the IDE.
  2. Select the Miscellaneous category in the Options window and click the Maven tab.
  3. Specify the location of your local Maven installation (requires 2.0.9 or newer).
  4. Check that the location of the local Maven repository is correct.
  5. Click OK to close the Options window.

If Maven is not installed on your system, you can download the installer from the Maven site.

Update your Maven repositories

Local and remote Maven repositories are used for code completion and when building projects. You should update the indexes for the Maven remote repositories to ensure that any artifacts you may need are readily available when you develop your project. You can configure how often the IDE checks for updates in the Maven tab of the Options window. You can perform an immediate check for updates and explore your local and remote Maven repositories from the Maven Repository Browser.

  1. Choose Window > Other > Maven Repository Browser.
  2. Click Update Indexes ( Update Indexes button  ) at the top of the Maven Repository Browser window.

When you click Update Indexes, the IDE will check and download the most recent index for each of your Maven remote repositories. An index represents the current state of the artifacts located in the repository and is used to provide a reference to the artifacts that are available to your application. By default, the IDE does not download an artifact from a repository until the artifact is explicitly required.

Note. Indexes are quite large and it can take some time to update them all.

For more details about using Maven in NetBeans IDE, see the section on Configuring Maven in the Creating a Maven Swing Application Using Hibernate tutorial and also Best Practices for Apache Maven in NetBeans IDE.

Creating the Maven Enterprise Application Project

The goal of this exercise is to create an enterprise application project using the Maven Enterprise Application archetype bundled with the IDE. The enterprise application archetype will also create an EJB project and a webapp project.

The IDE includes several Maven archetypes in the New Project wizard to help you quickly create common NetBeans project types such as enterprise application projects (EAR), web application projects (WAR) and EJB module projects (JAR). The wizard also enables you to create projects from archetypes in registered remote repositories.

  1. Choose File > New Project (Ctrl-Shift-N) from the main menu.
  2. Select Maven Enterprise Application from the Maven category. Click Next.
    Maven Enterprise Application project type in the New Project wizard
  3. Type MavenEnterpriseApp for the the Project Name and set the Project Location.
  4. (Optional) Modify the artifact details. Click Next.
    Project details in the New Project wizard
  5. Set the Java EE Version to Java EE 6.
  6. Select Create EJB Module and Create Web App Module. Click Finish.

When you click Finish, the IDE creates the following projects from the Maven Enterprise Application archetype.

  • EJB. The EJB project generally contains the source code with the business logic of the application. The EJB project is packaged as an EJB JAR archive.
  • Webapp. The Webapp project generally contains the presentation layer of the application such as JSF and JSP pages and servlets. The Webapp project may also contain source code with business logic. The Webapp project is packaged as a WAR archive.
  • Assembly. The Assembly project is used to assemble an EAR archive from the EJB and WAR archives. The Assembly project does not contain any sources.
  • Enterprise Application. The Enterprise Application project does not contain any sources. The Enterprise Application only contains a POM file (pom.xml) with details about the modules contained in the enterprise application.
Projects window showing generated projects

After you create the enterprise application project, the Assembly project is badged because some dependencies are unavailable. If you expand the Libraries node for the MavenEnterpriseApp-ear JavaEE6 Assembly project, you can see that the project requires libraries that are either missing or not on the classpath.

In the Projects window, you can right-click the "non-classpath dependency" node and choose Expand Dependencies to see the missing dependencies.

The Assembly project has dependencies on the JAR and WAR that will be packaged and available after you compile the EJB project and the webapp project. You can see that the artifacts MavenEnterpriseApp-ejb and MavenEnterpriseApp-web are listed as dependencies in the POM for the Assembly project.

Coding the EJB Project

The EJB project contains the business logic of the application. In this application the GlassFish container will manage transactions using the Java Transaction API (JTA). In this tutorial you will create an entity class, a message-driven bean and a session facade for the entity class in the EJB project.

Specify the target server.

When developing Maven applications you typically do not need to specify an application server until you build the application. However, to take advantage of some of the code generation features in the IDE, for this tutorial you will set the target server before you start writing your code. By setting the deployment server, the IDE is able to recognize the technologies supported by the server and enable various options in some wizards to generate code that is optimized for that server.

  1. Start the GlassFish server.
  2. Right-click the EJB project node in the Projects window and choose Properties.
  3. Select the Run category in the Properties window.
  4. Select the GlassFish Server. Click OK.

By specifying GlassFish as the deployment server before coding, the IDE will enable the option of selecting JTA in the wizard for creating the persistence unit. You can also select to use any of the datasources registered with the server.

Note. If you do not specify GlassFish Server 3, the default transaction type when you create the persistence unit will be RESOURCE-LOCAL. You will need to edit the persistence.xml file manually to specify JTA if you want the container to manage the transactions. You will also need to specify a database connection instead of a registered data source in the New Persistence Unit wizard.

Creating the Persistence Unit

In this exercise you create a persistence unit in the EJB project. The persistence unit specifies the database connection details and specifies how transactions are managed. For this application you will specify JTA in the New Persistence Unit wizard because you want the GlassFish server to manage the transactions.

To create the persistence unit, perform the following steps.

  1. Right-click the EJB project node and choose New > Other from the popup menu to open the New File wizard.
  2. Select Persistence Unit from the Persistence category. Click Next.
  3. Select EclipseLink as the Persistence Provider in the New Persistence Unit dialog box.
  4. Select a datasource (for example, select jdbc/sample if you want to use JavaDB).

    The datasource jdbc/sample is bundled with the IDE when you install the IDE and the GlassFish server, but you can specify a different datasource if you want to use a different database.

    You can keep the other default options (persistence unit name, EclipseLink persistence provider).

  5. Ensure that Use Java Transaction APIs is selected and that the Table Generation Strategy is set to Create so that the tables based on your entity classes are created when the application is deployed. Click Finish.
New Persistence Unit wizard

When you click Finish, the IDE creates the XML file persistence.xml and opens the file in the editor. In the Projects window, you can see that the file was created in the Other Sources > src/main/resources > META-INF directory. The file contains details about connecting to the database and how transactions are managed. If you click XML in the editor, you can see the following elements in persistence.xml.

<persistence-unit name="com.mycompany_MavenEnterpriseApp-ejb_ejb_1.0-SNAPSHOTPU" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/sample</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
</persistence-unit>
            

You can see that JTA is specified as the transaction type and that the application will use the registered datasource jdbc/sample.

Creating the Entity Class

In this exercise you will create an entity class in the EJB project to represent the objects that will be persisted to the database. To create the NewsEntity entity class, perform the following steps.

  1. Right-click the EJB module in the Projects window and choose New > Other to open the New File wizard.
  2. Select Entity Class from the Persistence category. Click Next.
  3. Type NewsEntity for the Class Name.
  4. Type ejb for the Package and leave the Primary Key Type as Long. Click Finish.

When you click Finish, the entity class NewsEntity.java opens in the Source Editor. In the Source Editor, add some fields by performing the following steps.

  1. Add the following field declarations to the class.
    private String title;
    private String body;
  2. Right-click in the Source Editor and choose Insert Code and select Getter and Setter in the popup menu.
  3. In the Generate Getters and Setters dialog box, select the body and title fields. Click Generate.
  4. Fix your imports and save your changes.

Creating the Message-Driven Bean

In this exercise you will create a message-driven bean in the EJB project. A message-driven bean is an enterprise bean that enables the asynchronous exchange of messages. The NewsApp application uses a message-driven bean to receive and process messages sent to the queue by a servlet in the web module.

To use a message-driven bean in an application, the connector resources used by the bean need to be registered with the server. When you are deploying to the GlassFish server, you can create the resources directly on the server through the Admin Console or you can create the resources on deployment by specifying the details in the sun-resources.xml file. When the application is deployed to the server, the server registers the resources based on sun-resources.xml. When you use the New File wizard in the IDE to create a message-driven bean, the IDE will generate the elements in sun-resources.xml for you.

In a Maven project, the sun-resources.xml file is located in the src/main/setup directory under the project node in the Files window.

  1. Right-click the EJB module in the Projects window and choose New > Other to open the New File wizard.
  2. From the Java EE category, select Message-Driven Bean. Click Next.
  3. Type NewMessage for the EJB Name.
  4. Select ejb from the Package drop-down list.
  5. Click the Add button next to the Project Destination field to open the Add Message Destination dialog box.
  6. In the Add Message Destination dialog box, type jms/NewMessage and select Queue for the destination type. Click OK.
    New Persistence Unit wizard
  7. Make sure that the project destination is correct. Click Finish.
    New Persistence Unit wizard

    When you click Finish, the IDE generates the bean class and adds the following annotations that identify the class as a message-driven bean and configuration properties.

    @MessageDriven(mappedName = "jms/NewMessage", activationConfig =  {
            @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
            @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
        })
    public class NewMessage implements MessageListener {
    
        public NewMessage() {
        }
    
        public void onMessage(Message message) {
        }
    }
  8. Inject the MessageDrivenContext resource into the class by adding the following annotated field to the class.
    public class NewMessageBean implements MessageListener {
    
    @Resource
    private MessageDrivenContext mdc;
    
  9. Introduce the entity manager into the class by adding the following annotated field (in bold).
    public class NewMessage implements MessageListener {
    
    @Resource
    private MessageDrivenContext mdc;
    @PersistenceContext(unitName="com.mycompany_MavenEnterpriseApp-ejb_ejb_1.0-SNAPSHOTPU")
    private EntityManager em;
                       

    The @PersistenceContext annotation specifies the context by declaring the persistence unit. The unitName value is the name of the persistence unit.

  10. Add the following save method (in bold).
    public NewMessage() {
    }
    
    public void onMessage(Message message) {
    }
    
    public void save(Object object) {
        em.persist(object);
    }
  11. Modify the onMessage method by adding the following (in bold) to the body:
    public void onMessage(Message message) {
         ObjectMessage msg = null;
         try {
              if (message instanceof ObjectMessage) {
              msg = (ObjectMessage) message;
                  NewsEntity e = (NewsEntity) msg.getObject();
                  save(e);
              }
         } catch (JMSException e) {
              e.printStackTrace();
              mdc.setRollbackOnly();
         } catch (Throwable te) {
              te.printStackTrace();
         }
    }
  12. Fix your import statements (Ctrl-Shift-I) and save your changes.

    Note: When generating the import statements, you want to make sure to import the jms and javax.annotation.Resource libraries.

For more details about message-driven beans, see the chapter What is a Message-Driven Bean? in the Java EE 6 Tutorial, Part I.

Creating the Session Bean

In this exercise you will use a wizard to create a session bean facade for the NewsEntity entity class. The wizard will generate some common methods create, edit and find methods that can be accessed from the servlets in the webapp project.

  1. Right-click the EJB module and choose New > Other.
  2. From the Persistence category, select Session Beans for Entity Classes and click Next.
  3. Select ejb.NewsEntity from the list of available entity classes and click Add to move the class to the Selected Entity Classes pane. Click Next.
  4. Check that the Package is set to ejb. You do not need to create a local interface.
  5. Click Finish.
New Persistence Unit wizard

In Java EE 6, interfaces are optional. In Java EE 5 you needed to create a local interface for the session bean and then call the session bean via the interface. In Java EE 6, the local interface is optional and the servlet in the web module can access the session bean directly via a no-interface facade.

Coding the Web Application

In this section you will create two servlets in the webapp project.

Creating the ListNews Servlet

In this exercise you will create the ListNews servlet that will be used to display a list of posted messages. You will use annotations to inject the session facade and access the findAll method and retrieve the posted messages.

  1. Right-click the web module project and choose New > Servlet.
  2. Type ListNews for the Class Name.
  3. Type web for the Package name. Click Finish.

    When you click Finish, the class ListNews.java opens in the Source Editor.

  4. Right-click in the Source Editor and choose Insert Code and select Call Enterprise Bean.
  5. In the Call Enterprise Bean dialog box, expand the NewsApp-ejb node and select NewsEntityFacade. Click OK.
    Call Enterprise Bean dialog

    When you click OK, the EJB resource is injected into the servlet using the @EJB annotation.

    @WebServlet(name = "ListNews", urlPatterns = {"/ListNews"})
    public class ListNews extends HttpServlet {
        @EJB
        private NewsEntityFacade newsEntityFacade;
  6. In the processRequest method, modify the method by uncommenting the code and adding the following lines (in bold) to the body of the method:
    out.println("<h1>Servlet ListNews at " + request.getContextPath () + "</h1>");
    
    List news = newsEntityFacade.findAll();
    for (Iterator it = news.iterator(); it.hasNext();) {
      NewsEntity elem = (NewsEntity) it.next();
      out.println(" <b>"+elem.getTitle()+" </b><br />");
      out.println(elem.getBody()+"<br /> ");
    }
    out.println("<a href='PostMessage'>Add new message</a>");
    
    out.println("</body>");
       
  7. Fix your imports (Ctrl-Shift-I) and save your changes.

    When generating the import statements, you want to import the java.util libraries.

Creating the PostMessage Servlet

In this exercise you will create the PostMessage servlet that will be used to post messages. You will use annotations to inject the JMS resources you created directly into the servlet, specifying the variable name and the name to which it is mapped. You will then add the code to send the JMS message and the code for the HTML form for adding a message.

  1. Right-click the web module project and choose New > Servlet.
  2. Type PostMessage for the Class Name.
  3. Select web for the Package name. Click Finish.

    When you click Finish, the class PostMessage.java opens in the Source Editor.

  4. In the Source Editor, use annotations to inject the ConnectionFactory and Queue resources by adding the following field declarations.
    @WebServlet(name="PostMessage", urlPatterns={"/PostMessage"})
    public class PostMessage extends HttpServlet {
       @Resource(mappedName="jms/NewMessageFactory")
       private  ConnectionFactory connectionFactory;
    
       @Resource(mappedName="jms/NewMessage")
       private  Queue queue;
  5. Fix your imports (Ctrl-Shift-I) to import the javax.jms libraries.
    New Persistence Unit wizard

    Note. If the IDE does not offer javax.jms as an option, you can search the repositories for the correct artifact by clicking the suggestion icon in the margin next to private ConnectionFactory connectionFactory; and choosing Search Dependency at Maven Repositories.

    New Persistence Unit wizard

    You can use the Search in Maven Repositories dialog to locate and select the artifact that contains ConnectionFactory.

    New Persistence Unit wizard
  6. Add the following code to send the JMS messages to the processRequest method.
    response.setContentType("text/html;charset=UTF-8");
    
    // Add the following code to send the JMS message
    String title=request.getParameter("title");
    String body=request.getParameter("body");
    if ((title!=null) && (body!=null)) {
        try {
            Connection connection = connectionFactory.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(queue);
    
            ObjectMessage message = session.createObjectMessage();
            // here we create NewsEntity, that will be sent in JMS message
            NewsEntity e = new NewsEntity();
            e.setTitle(title);
            e.setBody(body);
    
            message.setObject(e);
            messageProducer.send(message);
            messageProducer.close();
            connection.close();
            response.sendRedirect("ListNews");
    
        } catch (JMSException ex) {
            ex.printStackTrace();
        }
    }
  7. Uncomment the code to print the HTML and add the web form for adding a message.
    out.println("Servlet PostMessage at " + request.getContextPath() + "</h1>");
    
    // The following code adds the form to the web page
    out.println("<form>");
    out.println("Title: <input type='text' name='title'><br/>");
    out.println("Message: <textarea name='body'></textarea><br/>");
    out.println("<input type='submit'><br/>");
    out.println("</form>");
    
    out.println("</body>");
        
  8. Fix your imports (Ctrl-Shift-I) and save your changes.

    Note. You want to import the javax.jms libraries for Connection, ConnectionFactory, Session and Queue.

Building the Application with Maven

Now that you are finished coding the application, you can use Maven to build the enterprise application. In this section you will build and package the projects in an EAR archive. The EAR archive will contain an EJB JAR archive and a WAR archive. After you create the EAR archive you can deploy the archive to the target server.

Working With Project Dependencies

In this exercise you will modify the pom.xml of the Webapp project to prevent the EJB archive from being included in the WAR when packaging. This will prevent the EAR archive from containing two copies of the EJB archive.

Each Maven project contains a pom.xml file that contains details about the contents of archives. Any external libraries that are required by the project are listed as dependencies in pom.xml. You can modify pom.xml to specify the dependencies that need to be included when packaging the archive.

In this application, the EJB JAR and the WAR archives will be packaged in an EAR archive. If you look at the pom.xml of the Assembly project, you can see that the EJB and WAR are declared as dependencies.

pom.xml of Assembly project

If you look at the pom.xml of the Webapp project, you can see that the EJB archive is declared as a dependency. The Webapp project requires the EJB archive as a dependency, but for this application you do not want the EJB archive to be included in the WAR during packaging. The EJB archive will be available and provided to the Webapp as part of the EAR archive.

pom.xml of Assembly project

You can right-click in pom.xml and choose Show Dependency Graph to see a visual representation of the project dependencies. You can place your cursor over an artifact to display a tooltip with the artifact details.

Code completion in pom.xml

Perform the following steps to modify the pom.xml of the Webapp project to add a scope element to the dependency on the EJB archive.

  1. Expand the Project Files node under the Webapp project.
  2. Double-click pom.xml to open the file in the editor.
  3. Modify the dependency on the MavenEnterpriseApp-ejb artifact by editing the POM to add the following <scope>provided</scope> element.
    <dependency>
        <groupId>com.mycompany</groupId>
        <artifactId>MavenEnterpriseApp-ejb</artifactId>
        <scope>provided</scope>
        <version>1.0-SNAPSHOT</version>
    </dependency>
  4. Save your changes.

You can use the code completion in the POM editor to help you edit the file.

Code completion in pom.xml

By declaring that the dependency is provided, Maven will not package the artifact when building the WAR archive.

Building with Dependencies

The Maven build framework proceeds through a specific sequence of phases, and each phase consists of one or more goals and can be configured to use various Maven plugins. The Build with Dependencies menu item is mapped to the install phase of the Maven build lifecycle and is configured to use the Reactor plugin. When you choose Build with Dependencies in the popup menu, Maven builds the application and any required dependencies and copies the build artifacts to the local repository.

You can modify how Maven phases and goals are mapped to menu actions in the Actions panel of the project's Properties dialog box.

To build the EAR archive, perform the following step.

  • Right-click the Assembly project node and choose Build with Dependencies.

When you build the Assembly project using the Reactor plugin, the dependencies of the sub-projects are built before the Assembly project is built. The Output window displays the build order.

Output window showing Reactor build order

The results of the build are also displayed in the Output window.

Output window showing Reactor build status

After you build the Assembly project, you can see the final EAR archive inside the target directory under the Assembly project node in the Files window.

Files window showing EAR archive

If you used the default artifact name com.mycompany, you can use the Maven Repository Browser to view the build artifacts by expanding com.mycompany in the Local Repository.

For more details about building Maven projects, see Maven - Introduction to the Build Lifecycle at maven.apache.org.

Deploying the EAR Archive

This section describes two methods for deploying the EAR archive to the server. You can deploy the application to the GlassFish server by using a menu action in the IDE or by using the Deploy tool in the GlassFish Admin Console.

Deploying From the IDE

In this exercise you will modify the Maven goal that is mapped to the Run action. After you modify the action you can use the Run action to deploy the EAR to the server.

  1. Right-click the Assembly project node in the Projects window and choose Properties.
  2. Select Actions from the list of Categories in the left panel of the Properties window.
  3. Select Run Project from the list of Actions in the right panel.
  4. In the Execute Goals text field, delete the package goal and type install. Click OK.
    Actions panel of the project Properties dialog
  5. Right-click the Assembly project node in the Projects window and choose Run.
  6. Select the GlassFish server in the Select Deployment Server dialog. Click OK.
    Select Deployment Server dialog

After you select the deployment server, the IDE creates the JMS resources on the server and deploys the EAR archive.

Deploying From the GlassFish Admin Console

In this exercise you will deploy the EAR archive using the Deploy tool in the GlassFish Admin Console.

  1. Expand the Servers node in the Services window.
  2. Start the GlassFish server.
  3. Right-click the GlassFish server node and choose View Admin Console to open the GlassFish Admin Console in your browser.
  4. Click the Applications node in the left pane of the Admin Console.
  5. Click the Deploy button in the main pane of the Admin Console.
  6. Click Browse to locate the EAR archive for the enterprise application.

    The EAR archive is located in the target directory inside the enterprise application directory on your local system.

  7. Click OK.

When you click OK, the GlassFish deploy tool deploys the application.

Note. If you deploy the application using the deploy tool, you will also need to manually create the resources that are required by the application if they do not exist.

Running the Application

In this exercise you will open the ListNews page of the application in your browser and add a message.

  1. Open your browser to the following URL to display the ListNews page.

    http://localhost:8080/MavenEnterpriseApp-web/ListNews.

    When you first run the project, the database is empty and there are no messages to display.

    ListNews page open in the browser
  2. Click Add Message.
  3. Type a message in the form in the PostMessage servlet. Click Submit Query.
    ListNews page open in the browser

When you add a message with the PostMessage servlet, the message is sent to the message-driven bean for writing to persistent storage, and the ListNews servlet is called to display the messages in the database. The list of messages in the database retrieved by ListNews often does not yet contain the new message because our message service is asynchronous.

Downloading the Solution Project

You can download the solution to this tutorial as a project in the following ways.

  • Download a zip archive of the finished project.
  • Checkout the project sources from the NetBeans Samples by performing the following steps:
    1. Choose Team > Subversion > Checkout from the main menu.
    2. In the Checkout dialog box, enter the following Repository URL:
      https://svn.netbeans.org/svn/samples~samples-source-code
      Click Next.
    3. Click Browse to open the Browse Repostiory Folders dialog box.
    4. Expand the root node and select samples/javaee/MavenEnterpriseApp. Click OK.
    5. Specify the Local Folder for the sources (the local folder must be empty).
    6. Click Finish.

      When you click Finish, the IDE initializes the local folder as a Subversion repository and checks out the project sources.

    7. Click Open Project in the dialog that appears when checkout is complete.

    Notes.



See Also

For more information about using NetBeans IDE to develop Java EE applications, see the following resources:

You can find more information about using Enterprise Beans in the Java EE 6 Tutorial.

To send comments and suggestions, get support, and keep informed on the latest developments on the NetBeans IDE Java EE development features, join the nbj2ee mailing list.