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.
This tutorial assumes that you have some prior knowledge of Java programming and development using NetBeans IDE.
Softwares required for this tutorial:
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:
So lets gets started with enterprise application development in NetBeans 6.0
The first step is to create a database to store the contact details. Follow the following steps:
![]() |
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.
In this step we will be creating a new enterprise application project in NetBeans 6.0. Follow following steps:
![]() |
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.
Now we will start developing an EJB module. In this step we will create following:
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:
![]() |
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.
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:
![]() |
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:![]() |
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.
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:
![]() |
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.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:
![]() |
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.
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:
![]() |
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.
We now move on to develop a Web Module. In this step we will create the following:
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:
![]() |
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: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.
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:
If for some reason you are unable to locate this file, you may create a new one. Follow the steps below:
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.
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:
![]() |
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;
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.![]() |
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.
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:
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.
| ContactDemoApplication.zip | ![]() |
194491 bytes |
| Screenshot-1.png | ![]() |
18054 bytes |
| Screenshot10.png | ![]() |
45772 bytes |
| Screenshot11.png | ![]() |
40895 bytes |
| Screenshot13.png | ![]() |
51380 bytes |
| Screenshot14.png | ![]() |
21902 bytes |
| Screenshot20.png | ![]() |
21817 bytes |
| Screenshot3.png | ![]() |
60160 bytes |
| Screenshot4.png | ![]() |
58870 bytes |
| Screenshot5.png | ![]() |
38819 bytes |
| Screenshot6.png | ![]() |
34961 bytes |
| Screenshot7.png | ![]() |
56453 bytes |
| Screenshot9.png | ![]() |
44863 bytes |