BeginningWithEnterpriseApplication

Beginning with Enterprise Application Development with NetBeans 6.0

This tutorial will guide you on how to begin developing an Enterprise Application using J2EE 5 features available in NetBeans 6. The tutorial will get you going as quickly as possible. We will be creating, deploying and executing an enterprise application module and a web client module.

Note that this tutorial was written for NetBeans 6.0. It should work with later versions of the IDE, but there will be minor differences in the user experience.

Prequisites:

This tutorial assumes that you have some prior knowledge of Java programming and development using NetBeans IDE.

Softwares required for this tutorial:

  1. Java Standard Development Kit 6
  2. NetBeans 6.0 with Web & J2EE pack

Tutorial Contents:

  1. Introduction to the tutorial application.
  2. Setting up the database.
  3. Creating enterprise application project
  4. Developing EJB module.
  5. Developing web module.
  6. Deploying and Running the project.
  7. Summary

Introduction to the tutorial application

In this tutorial we will be creating an application which will allow a user to create new contacts. These contacts will made visible in a tabular format.

To complete this tutorial we will be using following technologies:

  1. Entity Beans
  2. Message Driven Beans
  3. Session Beans
  4. Web Service
  5. JSP
  6. Servlets
  7. Web Service Clients

So lets gets started with enterprise application development in NetBeans 6.0

Setting up the database

The first step is to create a database to store the contact details. Follow the following steps:

  1. Choose Tools > Java DB Database > Start Server
  2. Choose Tools > Java DB Database > Create Database
  3. Enter the Database Name as PIM
  4. Enter Username as contact
  5. Enter Password as pass
  6. Keep the default database location.
  7. Click OK.

File:Screenshot-1_BeginningWithEnterpriseApplication.png

In step 1 we started the Java DB Database server in order to create a new database. From Step 2 through 6 we entered the new database information as “PIM” with username as “contact” and password as “pass”. On clicking OK NetBeans 6.0 creates a new database named “PIM” for us. This will create a new connection for the newly created database inside NetBeans. You may have a look at this by clicking Services Tab on left hand side screen and then expanding Database tree node.

Creating enterprise application project

In this step we will be creating a new enterprise application project in NetBeans 6.0. Follow following steps:

  1. Choose File > New Project.
  2. From the categories pane, select Enterprise.
  3. From the projects pane, select Enterprise Application. Click Next
  4. Enter the project name as ContactDemoApplication.
  5. Leave default project location, project folder, server(GlassFish V2), Java EE Version (Java EE 5).
  6. Select Create Application Client Module.
  7. Click Finish.

File:Screenshot3_BeginningWithEnterpriseApplication.png

Step 1 will open a “New Project” dialog. Step 2 and 3 will command NetBeans to create a New Enterprise Application project. Step 4 to 7 will create a new enterprise application named “ContactDemoApplication” with a desktop client module in Java EE 5. The server used will be GlassFish V2.

Developing EJB module

Now we will start developing an EJB module. In this step we will create following:

  1. A persistence unit- persistence.xml
  2. An Entity Bean – Contact.java
  3. A Message-Driven Bean – NewContactMessageBean.java
  4. A Session Bean – ContactFacade.java
  5. A Web Service – ContactWeb.java

Creating a Persistence Unit

A J2EE 5 application uses a persistence unit to define a datasource and an entity manager which are together used to access databases. It is a configuration unit in XML which stores the information about the persistence provider such as hibernate, TopLink etc. and the database. To create a persistence unit follow the steps below:

  1. Right click EJB module (ContactDemoApplication-ejb) and choose New > Other.
  2. From the Persistence category, select Persistence Unit and click Next.
  3. Leave the default persistence unit name (ContactDemoApplication-ejbPU2) and also the default Persistence Provider (TopLink).
  4. For the Data Source, you need to create a New Data Source by selecting New Data Source option from the drop down.
  5. In Create Data Source window enter the JNDI name as jdbc/PIM and select database connection as the one that was newly added in services tab on creating the new database earlier. Click OK.
  6. Make sure Use Java Transactions APIs is selected.
  7. Choose Table Generation Strategy as Create.
  8. Click Finish.

File:Screenshot4_BeginningWithEnterpriseApplication.png

These steps simply create a new persistence unit. Step 4 and 5 define a new datasource that points to the database named PIM through a JNDI name jdbc/PIM which was created earlier.

Creating an Entity Bean

Entity Beans in J2EE 5 corresponds to a persistent data or simply a database table. In our demo application we require to save contacts information in the database including name, e-mail, phone, city, country. Our contact application, therefore requires only a single Entity Bean named Contact which will correspond to a CONTACT table in the database. To create an entity bean follow the steps below:

  1. Right click EJB module (ContactDemoApplication-ejb) and choose New > Other
  2. From the Persistence category, select Entity Class and Click Next.
  3. Enter Class Name as Contact.
  4. Enter Package Name as org.entities.
  5. Click Finish.

File:Screenshot5_BeginningWithEnterpriseApplication.png

These steps will simply create a new entity bean named Contact and open it in NetBeans Source editor. currently it has only one field named “id” which will act as the unique identifier for each instance of this class. It can also be viewed as the primary key of the CONTACT table.

We now need to define a few more fields into Contact.java. Follow the following steps:

1. Add following declaration to the class:

	@Entity
	public class Contact implements Serializable {
	    private static final long serialVersionUID = 1L;
	    private Long id;
	    private String name;
	    private String email;
	    private String phone;
	    private String city;
	    private String country;

2. Now Right click the source editor and choose Refactor > Encapsulate Fields to generate getters and setters for the newly added fields. In the resulting dialog box, you need to select getter and setter checkboxes for following fields:

File:Screenshot6_BeginningWithEnterpriseApplication.png

3. Click Refactor.
4. Save the changes to the file.

After these steps go through the code of Contact.java and you will find that the getters and setters for all the added fields have been generated by NetBeans. This completes the creation of our Contact Entity Bean.

Creating a Message-Driven Bean

A message-driven bean allows J2EE application to recieve and process message asynchronously. These messages may be recieved from either a client application, another enterprise bean or a web component. In our application, we need to create a message-driven bean which on recieving a message from either a web or desktop client, creates a new contact into the database. The contact parameters will be sent by the client applications. Follow the steps below:

  1. Right click EJB module (ContactDemoApplication-ejb) and choose New > Other
  2. From Enterprise Category, select Message-Driven Bean and Click Next.
  3. Enter the EJB Name as NewContactMessage.
  4. Enter the package name as org.message.
  5. To select the Project Destination, Click Add button.
  6. Enter jms/contact as the Destination Name, Select Destination Type as Queue and Click OK to close the dialog.
  7. Click Finish.

File:Screenshot7_BeginningWithEnterpriseApplication.png


This will open up NewContactMessageBean.java in the NetBeans editor. Here, the annotations added by NetBeans tell the container that the component is the message-driven bean and JMS resource used by the bean as Queue mapped by a JNDi resource named jms/contact. The annotations are used to avoid configuration file creation and also to introduce and use the resources directly into the class.The onMessage method is invoked by the conatiner whenever a message is recieved in the queue. The business logic to handle the processing of the message may be added here. To make our message-driven bean functional we now need to introduce some more annotations and code to create new contact in the database as follows:

1. Add following annotations to add new MessageDrivenContext into the class, which will be used later to call setRollbackOnly() method to handle exceptions in business logic.

	public class NewContactMessageBean implements MessageListener {
		@Resource
		MessageDrivenContext messageDrivenContext;

2. Introduce EntityManager, to create new contact into the database, by right clicking on the source editor and selecting Persistence > Use Entity Manager. This will add the following code:

	@PersistenceContext
	private EntityManager em;

This will also add a new method:

	public void persist(Object object) {
   	    em.persist(object);
    	}	

Rename this method as save(Object object) as follows:

	public void save(Object object) {
	    em.persist(object);
    	}

3. Method onMessage needs to be modified to add the business logic to store the new contact into the database as follows:

	public void onMessage(Message message) {
        	    try {
          		ObjectMessage objectMessage = (ObjectMessage) message;
		Contact contact = (Contact) objectMessage.getObject();
            	save(contact);
	    } catch (JMSException ex) {
          		messageDrivenContext.setRollbackOnly();
        	    }
    	}

The code snippet above first casts the recieved message to ObjectMessage. It then gets the Contact object from it and finally calls saves it into the database.
4. Right Click on the source editor and select Fix Imports to automatically import the required classes.
5. Save the modified file.

Creating a Session Bean

A session bean is used by the client to access the application deployed on the server. There are basically two types of session beans namely, Stateful and Stateless. Stateful session bean preserves the state of the unique client-bean session in form of its instance variables. On the other hand, stateless session beans does not mantains conversational state with the clients. For our demo application we just require a single stateless session bean which would later be used by web and desktop clients to access all the contacts for viewing purposes. Also our stateless session bean won't be accessed directly, but by the means of a web service. Follow the steps below:

  1. Right click EJB module (ContactDemoApplication-ejb) and choose New > Other.
  2. From Persistence category, select Session Bean For Entity Classes and click Next.
  3. Select org.entities,Contact from Available Entity Classes list and Click Add.
  4. Select Include referenced classes and Click Next.
  5. Leave the default project name (ContactDemoApplication-ejb).
  6. For Package, enter org.session
  7. Leave default for created files.
  8. Select Local and click Finish.

File:Screenshot9_BeginningWithEnterpriseApplication.png

The steps above creates a new stateless session bean named ContactFacade.java which acts as a facade and gives access to the Contact Entity Bean. If you browse through the code, you will find some of the utility methods automatically created by NetBeans. These method include create, edit, remove, find and findAll. We require no further changes in this session bean.

Creating a Web Service

Web Services are Web Based Applications that use Open, XML-based standards and transport protocols to exchange data. Web Services are reusable software components that semantically encapsulate discrete functionality and are accessible over Standard Protocols such as SOAP. In our application, we will create a Web Service that will encapsulate the Session Bean, we created in previous section. This would allow both desktop and web client applications to access the functionalities provided by ContactFacade by means of a standard protocol. Follow the steps below:

  1. Right Click the EJB Module (ContactDemoApplication-ejb) and select New > Other.
  2. From the Web Services category, select Web Service. Click Next
  3. Enter the Web Service Name as ContactWeb
  4. Enter the Package Name as org.webservice
  5. Select Create from Existing Session Bean and click Browse.
  6. Expand Enterprise Beans Node, select ContactFacade and click OK.
  7. Click Finish.

File:Screenshot10_BeginningWithEnterpriseApplication.png

The above steps create a new Web Service which encapsulates ContactFacade. The resulting ContactWeb.java file is opened in the NetBeans Design editor.

You are now recommended to browse through the EJB Module source code. But for our demo application this is all we need to complete the development of the EJB Module i.e. ContactDemoApplication-ejb.

Developing Web Module

We now move on to develop a Web Module. In this step we will create the following:

  1. A Servlet.
  2. A JSP.
  3. A Web Service Client.

Creating a Servlet

A Java Servlet extends the existing capabilities of the web server and allows a web application developer to add dynamic content to the it. A Servlet is an object that recieves request and generates responses based on that request. In larger applications, it may act as a controller. In our application, we need to create a Servlet which on recieving the request, will create new contact by sending a message to the Message-Driven bean. It would then generate a response and send it back to the page. Follow the steps below:

  1. Right click the Web Module (ContactDemoApplication-war) and select New > Other.
  2. From Web Category, Select Servlet and Click Next.
  3. Enter the Class Name as NewContact.
  4. Leave the default project (ContactDemoApplication-war).
  5. Enter the package name as org.servlets and Click Next.
  6. Select Add information to deployment descriptor (web.xml).
  7. Leave default Servlet Name and URL Pattern.
  8. Click Finish.

File:Screenshot11_BeginningWithEnterpriseApplication.png

The above steps simply creates a new Servlet named NewContact.java. However, to make it functional we need to add some code into it as follows:

    public class NewContact extends HttpServlet {
   
	@Resource(mappedName="jms/contactFactory")
  	private ConnectionFactory connectionFactory;
        
	@Resource(mappedName="jms/contact")
    	private Queue queue;

Adding this code injects the ConnectionFactory and Queue resources. These will then be used to send the JMS message. To send the JMS message we need to modify the processRequest method as follows:

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
        String name = request.getParameter("name");
        if(name==null || name.trim().equals(""))
        {
            request.setAttribute("message", "<font color='red'><b>Name is the required field</b></font>");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String city = request.getParameter("city");
        String country = request.getParameter("country");

        Contact contact = new Contact();
        contact.setName(name);
        contact.setEmail(email);
        contact.setPhone(phone);
        contact.setCity(city);
        contact.setCountry(country);
        
        try {
            Connection connection = connectionFactory.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = (MessageProducer) session.createProducer(queue);
            ObjectMessage objectMessage = session.createObjectMessage();
            objectMessage.setObject(contact);
            messageProducer.send(objectMessage);
            
            request.setAttribute("message", "<font color='blue'><b>Contact created successfully! Enter new contact details below:</b></font>");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
            
        } catch (JMSException ex) {
            Logger.getLogger(NewContact.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("message", "<font color='red'><b>Error creating contact: "+ex.getMessage()+". Try Again.</b></font>");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        } 
    } 

As you can make out from the code above:

  1. We first verify whether a name is available in the request. If not we send back an error message to index.jsp, otherwise, we get all other parameters and create a new Contact instance.
  2. We then create a new Connection using connectionFactory.
  3. Next, we create a session which is further used to create a MessageProducer with the destination queue pointing to jms/contact.
  4. Also the same session is used to create an ObjectMessage instance.
  5. The Contact instance created, on the basis of the parameters recieved from the JSP (index.jsp) is then encapsulated in this objectMessage and sent by the messageProducer to the destination queue.
  6. Finally, we set an attribute named message in the request and forward it back to JSP (index.jsp).

Make sure your imports are as follows:

import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.servlet.*;
import javax.servlet.http.*;
import org.entities.Contact;

To add imports automatically, right click the editor and select Fix Imports. This completes servlet creation.

Creating a JSP

JSP are fast and easy way to create a web application. They are usually used to create the presentation tier of the web application i.e. to develop the frontends that are dynamic in nature. In our application, we require a single JSP file that allows the user to enter and submit contact details which is to be created in the database. NetBeans, by default, creates a JSP named index.jsp inside the web module. To open it for editing, follow the steps below:

  1. Select Projects Tab.
  2. Expand ContactDemoApplication-war > Web Pages node.
  3. Double Click index.jsp to open.


If for some reason you are unable to locate this file, you may create a new one. Follow the steps below:

  1. Right click the Web Module (ContactDemoApplication-war) and select New > Other.
  2. From Web Category, Select JSP and Click Next.
  3. Enter JSP File name as index
  4. Select Location as Web Pages.
  5. Leave Folder as blank.
  6. Select JSP File (Standard Syntax) and Click Finish.

Both of the above steps will open index.jsp file in NetBeans Source Editor. Now we will first add a form into index.jsp inside the <body> tag which will allow user to enter new contact details and submit it to the Servlet (NewContact.java), we created earlier. Any existing code inside <body> tag will be replaced by:

    <body>
        <form action="NewContact" method="POST">
            <table border="0">
                <tr>
                    <td>Name:</td>
                    <td><input type="text" name="name" value="" /></td>
                </tr>
                <tr>
                    <td>E-Mail:</td>
                    <td><input type="text" name="email" value="" /></td>
                </tr>
                <tr>
                    <td>Phone:</td>
                    <td><input type="text" name="phone" value="" /></td>
                </tr>
                <tr>
                    <td>City:</td>
                    <td><input type="text" name="city" value="" /></td>
                </tr>
                <tr>
                    <td>Country:</td>
                    <td><input type="text" name="country" value="" /></td>
                </tr>
                <tr>
                    <td> </td>
                    <td> </td>
                </tr>
                <tr>
                <td><input type="submit" value="Submit" /></td>
                    <td> </td>
                </tr>
            </table>
        </form>
    </body>

TIP: In NetBeans, you may use Pallette to drag and drop html components to the source editor to create the web page quickly.

Now just below the start of the <body> tag, we need to add handler which will handle the message sent back to index.jsp from the servlet in case of both success and failure of creation of the contact
.

   
 <body>
    <%
            String message = (String) request.getAttribute("message");
            if(message!=null && !message.trim().equals(""))
            {
                out.println("<p>"+message+"</p>");
            }else
            {
                out.println("<p><font color='blue'><b>Enter new contact details below:</b></font></p>");
            }
     %>

For your reference, the complete code listing in index.jsp uptil this step is as follows:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
            String message = (String) request.getAttribute("message");
            if(message!=null && !message.trim().equals(""))
            {
                out.println("<p>"+message+"</p>");
            }else
            {
                out.println("<p><font color='blue'><b>Enter new contact details below:</b></font></p>");
            }
        %>
        <form action="NewContact" method="POST">
            <table border="0">
                <tr>
                    <td>Name:</td>
                    <td><input type="text" name="name" value="" /></td>
                </tr>
                <tr>
                    <td>E-Mail:</td>
                    <td><input type="text" name="email" value="" /></td>
                </tr>
                <tr>
                    <td>Phone:</td>
                    <td><input type="text" name="phone" value="" /></td>
                </tr>
                <tr>
                    <td>City:</td>
                    <td><input type="text" name="city" value="" /></td>
                </tr>
                <tr>
                    <td>Country:</td>
                    <td><input type="text" name="country" value="" /></td>
                </tr>
                <tr>
                    <td> </td>
                    <td> </td>
                </tr>
                <tr>
                <td><input type="submit" value="Submit" /></td>
                    <td> </td>
                </tr>
            </table>
        </form>
    </body>
</html>

This completes the JSP file creation. At this point, you may like to test your application on the browser. If so, go through the Deploying and Running Project section first and then continue the tutorial.

We will now proceed to create a Web Service Client.

Creating a Web Service Client

In this section, we will create a Web Service Client and will use it in our JSP (index.jsp) to display the already entered contacts in tabular format. This Web Service Client will act as the client of ContactWeb Web Service we created earlier. Follow the steps below:

  1. Build and Deploy the code (refer to Deploying and Running Project section).
  2. Right Click Web Module (ContactDemoApplication-war) and Select New > Other.
  3. From Web Services category, select Web Service Client and Click Next.
  4. Select Project and Click Browse to open Browse Web Services Window.
  5. Expand ContactDemoApplication-ejb and Select ContactWeb.
  6. In Package, enter org.webservices.client (Note: In NetBeans IDE 6.5 and later, this menu is disabled. Instead, the package name is computed from the WSDL namespace.)
  7. Click Finish.

File:Screenshot13_BeginningWithEnterpriseApplication.png

This will create a new Web Service Client for you. You may now like to browse through the generated files.

We will now use the Web Service Client in index.jsp as follows;

  1. Point your active cursor just below the <form> tag.
  2. Right Click and select Web Services Client Resources > Call web Service Operation.
  3. Expand ContactDemoApplication-war > ContactWeb > ContactWebService > ContactWebPort.
  4. Select findAll and click OK.

These steps will generate following code in index.jsp:

    <%-- start web service invocation --%><hr/>
    <%
    try {
	org.webservices.client.ContactWebService service = new org.webservices.client.ContactWebService();
	org.webservices.client.ContactWeb port = service.getContactWebPort();
	// TODO process result here
	java.util.List<org.webservices.client.Contact> result = port.findAll();
	out.println("Result = "+result);
    } catch (Exception ex) {
	// TODO handle custom exceptions here
    }
    %>
    <%-- end web service invocation --%><hr/>

We simply need to modify the above code as follows:

        <table>
            
            <tr>
                <td width="5%">Id</td>
                <td width="20%">Name</td>
                <td width="30%">E-Mail</td>
                <td width="15%">Phone</td>
                <td width="15%">City</td>
                <td width="15%">Country</td>
            </tr>
            
            <%-- start web service invocation --%>
            <%
            try {
                org.webservices.client.ContactWebService service = new org.webservices.client.ContactWebService();
                org.webservices.client.ContactWeb port = service.getContactWebPort();
                // TODO process result here
                java.util.List<org.webservices.client.Contact> result = port.findAll();
                
                for(org.webservices.client.Contact contact : result)
                {
                    out.println("<tr>");                
                    out.println("<td>"+contact.getId()+"</td>");
                    out.println("<td>"+contact.getName()+"</td>");
                    out.println("<td>"+contact.getEmail()+"</td>");
                    out.println("<td>"+contact.getPhone()+"</td>");
                    out.println("<td>"+contact.getCity()+"</td>");
                    out.println("<td>"+contact.getCountry()+"</td>");
                    out.println("</tr>");
                }
                
            } catch (Exception ex) {
                // TODO handle custom exceptions here
            }
            %>
            <%-- end web service invocation --%>
        </table>

In the above code we have simply added some formatting code and then we get the id, name, email, phone, city and country from contact object and display it in tabular format.

File:Screenshot20_BeginningWithEnterpriseApplication.png

With this we complete the creation of Web Module of our demo application. You may now build, deploy and run the code in the web browser to see the results.

Deploying and Running The Project

Now lets move on to deploying and running our ContactDemoApplication project. We will first clean build our application, deploy it on GlassFish server and then run it on the web browser. Follow the steps below:

  1. In the Projects tab, right-click the ContactDemoApplication project node and select Clean and Build to build the project.
  2. Again right-click the ContactDemoApplication project node and select Undeploy and Deploy to deploy the application on the GlassFish Server.
  3. Finally, right-click the ContactDemoApplication project node and this time select Run. This will open up the web browser and point to index.jsp.

Summary

In this tutorial we created an enterprise application with a web client interface that allows the user to create a new contact and at the same time displays the contact information after insertion in tabular format.

-- By Arpit Agarwal


This work is licensed under the Creative Commons Attribution 2.5 India License. To view a copy of this license, visit http://creativecommons.org/licenses/by/2.5/in/ or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.

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