SlideShare a Scribd company logo
Choose page language   Search:




HOME / Docs & Support / NetBeans 5.5



EJB 3.0 Enterprise Beans                                                                                                      Learning Trails
This document takes you through the basics of developing an enterprise application using EJB 3.0                                Basic Java Programming

technology which is part of the Java EE 5 platform. This document shows how the EJB 3.0                                         Java GUIs and Project Matisse
technology can simplify the process of developing enterprise applications. This document uses the                               Web Applications
NetBeans IDE 5.5 Release.
                                                                                                                                Java EE Applications
                                 Expected duration: 30 minutes                                                                  Mobile Applications
                                                                                                                                SOA Applications and UML
   Prerequisites                                                                                                                NetBeans Modules and Rich-
   This document assumes you have some basic knowledge of, or programming experience with,                                      Client Applications
   the following technologies:

      Java Programming
                                                                                                                              Docs for Packs
      NetBeans IDE                                                                                                              Mobility Pack
                                                                                                                                Visual Web Pack
   Software Needed for the Tutorial
                                                                                                                                Enterprise Pack
   For this tutorial you need to have the following software installed on your computer:
                                                                                                                                C/C++ Pack
      NetBeans IDE 5.5 (download).                                                                                              Profiler

      Java Standard Development Kit (JDK) version 5.0 or version 6.0 (download)                                                 UML Module

      Sun Java System Application Server, Platform Edition 9 (download)

   For this tutorial you need to register a local instance of Sun Java System Application Server                              Additional Resources
   with the IDE.                                                                                                                FAQs
                                                                                                                                Sample Applications
   Tutorial Exercises                                                                                                           Support
      Setting Up the Enterprise Application Project                                                                             Training
      Coding the EJB Module                                                                                                     NetBeans 5.0 Docs

      Coding the Web Module                                                                                                     NetBeans 6.0 Preview Docs
                                                                                                                                Contribute Documentation!
      Running the Project

      Troubleshooting



Setting Up the Enterprise Application Project
The goal of this exercise is to create the NewsApp enterprise application project containing an EJB
module and a web module. The NewsApp application uses a message-driven bean to receive and
process messages sent to the queue by a servlet. The application uses servlets to send messages
to the message-driven bean and to display messages.


   Creating an Enterprise Application

      1.   Choose File > New Project (Ctrl-Shift-N) from the main menu.

      2.   Select Enterprise Application from the Enterprise category and click Next.

      3.   Name the project NewsApp and set the server to Sun Java System Application Server.

      4.   Set the J2EE Version to Java EE 5, and select Create EJB Module and Create Web
           Application Module, if unselected.

      5.   Click Finish.



   Summary
   In this exercise we created a Java EE 5 enterprise application containing an EJB module and a
   web module.



Coding the EJB Module
In this exercise we will create the objects in the EJB module. We will create an entity class, a
message-driven bean and a session facade. We also will create a persistence unit to provide the
container with information for managing our entities, and the Java Message Service (JMS)
resources that our message-driven bean will use.


   Creating a Persistence Unit
   First we create a persistence unit that defines the data source and entity manager used in our
   application.



      1.   Right-click the EJB module and choose New > File/Folder.

      2.   From the Persistence category, select Persistence Unit and click Next.
3.   Keep the default Persistence Unit Name.

   4.   For the Persistence Provider, choose TopLink (default).

   5.   For the Data Source, choose the default data source jdbc/sample.

   6.   Check that the persistence unit is using the Java Transaction API and that the Table
        Generation Strategy is set to Create so that the tables based on our entity classes are
        created when the application is deployed.

   7.   Click Finish.




When you click Finish, the IDE creates persistence.xml and opens it in the Source Editor in
Design view. Close persistence.xml.


Creating the NewsEntity Entity Class
In this exercise we will create the NewsEntity entity class. An entity class is a simple Java
class. When you create the entity class, the IDE adds the @Entity annotation to define the
class as an entity class. After we create the class, we will create fields in the class to represent
the data that we want in our table.

Each entity class must have a primary key. When you create the entity class, the IDE adds the
@Id annotation to declare which field to use as the primary key. The IDE also adds the
@Generated annotation to specify the key generation strategy for the primary Id.

To create the NewsEntity class, do the following:



   1.   Right-click the EJB module in the Project window and choose New > File/Folder to open
        the New File wizard.

   2.   From the Persistence category, select Entity Class and click Next.

   3.   Type NewsEntity for the class name, 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, do the following:



   1.   Add the following field declarations to the class:



         String title;
         String body;


   2.   Right-click in the Source Editor and choose Refactor > Encapsulate Fields to generate
        getters and setters for each of the fields. In the Encapsulate Fields dialog box, make
        sure that getter and setter checkboxes are selected for the fields id, title and body.

   3.   Click Next in the Encapsulate Fields dialog box and then click Do Refactoring in the
        Refactoring tab of the Output window. The IDE adds the getter and setter methods for
        the fields and changes the visibility of the fields to private.

   4.   Save your changes to the file.


In the next step we will create the NewMessage message-driven bean.


Creating the NewMessage Message-Driven Bean
Now we will create the NewMessage message-driven bean in our EJB module. We will use the
New Message-Driven Bean wizard to create the bean and the necessary JMS resources.

To create the NewMessage message-driven bean, do the following:
1.   Right-click the EJB module in the Projects window and choose New > File/Folder to open the New File
        wizard.

   2.   From the Enterprise category, select Message-Driven Beans and click Next.

   3.   Type NewMessage for the class name.

   4.   Select ejb from the Package drop-down list.

   5.   Select Queue as the Destination Type and click Finish.


When you click Finish, the new message-driven bean class NewMessage.java opens in the Source Editor. You
can see that the class has the following annotation:



 @MessageDriven(mappedName = "jms/NewMessage")


This annotation tells the container that the component is a message-driven bean and the JMS resource used by
the bean. When the IDE generates the class, the Mapped Name of the resource (jms/NewMessage) is derived
from the name of the class (NewMessage.java). The JMS resource is mapped to the JNDI name of the
destination from which the bean receives messages. The New Message-Driven Bean wizard has already created
the JMS resources for us. The EJB 3.0 API enables us to look up objects in the JNDI namespace from within the
bean class so that we do not need to configure deployment descriptors to specify the JMS resources.

The EJB 3.0 specifications allow us to use annotations to introduce resources directly into a class. We will now
use annotations to introduce the MessageDrivenContext resource into our class, and then inject the
PersistenceContext resource which will be used by the EntityManager API to manage the persistent entity
instances. We will add the annotations to the class in the Source Editor.



   1.   Inject the MessageDrivenContext resource into the class by adding the following annotated field (in
        bold) to the class:



         public class NewMessage implements MessageListener {

         @Resource
         private MessageDrivenContext mdc;


   2.   Introduce the entity manager into the class by right-clicking in the code and selecting Persistence > Use
        Entity Manager from the pop-up menu.
        This adds the following annotation to your source code:



         @PersistenceContext
         private EntityManager em;


        and generates the following method in your code:



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


   3.   Modify the persist method to change the name to save. The method should look like the following:



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


   4.   Modify the onMessage method by adding the following to the body:



               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();
               }


   5.   Press Alt-Shift-F to generate any necessary import statements. When generating the import statements,
we want to make sure we import the jms and javax.annotation.Resource; libraries.

      6.   Save the file.



   Creating the Session Bean
   Next we create a session facade for the NewsEntity entity class. To create the session facade, do the following:



      1.   Right-click the EJB module and choose New > File/Folder.

      2.   From the Persistence category, select Session Beans for Entity Classes and click Next.

      3.   From the list of available entity classes, select NewsEntity and click Add and then click Next.

      4.   Check that the Package is set to ejb and that a local interface will be created.

      5.   Click Finish.


   When you click Finish, the session facade class NewsEntityFacade.java is created and opens in the Source
   Editor. The IDE also creates the local interface NewsEntityFacadeLocal.java.

   EJB 3.0 technology simplifies the creation of session beans by reducing the amount of required code. You can see
   that the annotation @Stateless is used to declare the class as a stateless session bean component and that the
   class no longer needs a statement implementing javax.ejb.SessionBean. The code is also much cleaner
   because with EJB 3.0 technology the business methods no longer need to have code declaring they throw
   checked exceptions.

   You can see that the PersistenceContext resource was injected directly into the session bean component
   when we created the session facade.


   Summary
   In this exercise, we coded an entity class and a message-driven bean in the EJB module. We then created a
   session facade for the entity class. We also created the JMS resources that will be used by our application.



Coding the Web Module
We will now create the servlets ListNews and PostMessage in our web module. These servlets will be used to read
and add messages.


   Creating the ListNews Servlet
   In this exercise we will create a simple servlet for displaying our data. We will use annotations to call our entity
   bean from our servlet.



      1.   Right-click the web module project and choose New > Servlet.

      2.   Type ListNews for the Class Name.

      3.   Enter web for the Package name and click Finish.


   When you click Finish, the class ListNews.java opens in the Source Editor. In the Source Editor, do the
   following:



      1.   Right-click in the source code and select Enterprise Resources > Call Enterprise Bean.

      2.   In the Call Enterprise Bean dialog box, select NewsEntityFacade and click OK. When you click OK, the
           entity bean resource is injected in the servlet using the @EJB annotation.

      3.   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>");




      4.   Press Alt-Shift-F to generate any necessary import statements for the class. When generating the import
           statements, we want to import classes from the util package.

      5.   Save the changes to the file.



   Creating the PostMessage Servlet
   In this exercise we will create the PostMessage servlet that will be used to post messages. We will use
annotations to inject the JMS resources we created directly into the servlet, specifying the variable name and the
name to which it is mapped. We 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.   Enter web for the Package name and click Finish.


When you click Finish, the class PostMessage.java opens in the Source Editor. In the Source Editor, do the
following:



   1.   Use annotations to inject the ConnectionFactory and Queue resources by adding the following field
        declarations (in bold):



         public class PostMessage extends HttpServlet {
             @Resource(mappedName="jms/NewMessageFactory")
             private ConnectionFactory connectionFactory;

               @Resource(mappedName="jms/NewMessage")
               private Queue queue;


   2.   We now add the code to send the JMS messages by adding the following code in bold 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();
               }
         }

         PrintWriter out = response.getWriter();




   3.   We now uncomment the code to print the HTML and add the web form for adding a message. Add the
        following lines in bold to the processRequest method



         out.println("Servlet PostMessage at " + request.getContextPath() + "</h1>");

         // Add the following code to add 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>");




   4.   Press Alt-Shift-F to generate any necessary import statements for the class.
        Note: When selecting the which libraries to import for Connection, ConnectionFactory, Session and
        Queue, make sure you import the java.jms libraries.
5.   Save your changes to the file.


Running the Project
We can now run our project. When we run the project, we want our browser to open to the page with the ListNews
servlet. We do this by specifying the URL in the Properties dialog box for our Enterprise Application. The URL is
relative to the context path for our application. After we enter the relative URL, we can build, deploy and run our
application from the Projects window.

To set the relative URL and run our application, do the following:



   1.    In the Projects window, right-click the NewsApp enterprise application node and select Properties in the pop-
         up menu.

   2.    Select Run in the Categories pane.

   3.    In the Relative URL textfield, type /ListNews.

   4.    Click OK.

   5.    In the Projects window, right click the NewsApp enterprise application node and choose Run Project.


When you run the project, the ListNews servlet opens in your browser and displays a list of the messages in the
database. When you first run the project, the database is empty, but you can click Add Message to add a message.




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.



Troubleshooting
The following are some of the problems you may encounter when creating your project.


   Problem with JMS Resources
   When using the wizard to create JMS resources, you may see the following server error message in the output
   window:



        [com.sun.enterprise.connectors.ConnectorRuntimeException:
                            JMS resource not created : jms/Queue]




   This message could indicate that the JMS resource was not created or was not registered with the application
   server. You can use the Admin Console of the Sun Java System Application Server to check, create and edit JMS
   resources.

   To open the Admin Console, do the following:



        1.   Confirm that the Sun Java System Application Server is running by expanding the Servers node in the
             Runtime of the IDE. A small green arrow next to the Sun Java System Application Server node indicates
             the server is running.

        2.   Right-click the Sun Java System Application Server node and choose View Admin Console to open the
             login window in your browser.
3.   Log in to the Sun Java System Application Server. The default user name and password are admin and
            adminadmin.

       4.   In the Admin Console in your browser, expand the Resources node and JMS Resources node in the left
            frame.

       5.   Click on the Connection Factories and Destination Resources links in the left frame to check if the
            resources are registered with the server and if necessary modify the resources. If the resources do not
            exist, you can create them in the Admin Console.


   You need to make sure that the JMS connection factory resource in the PostMessage servlet is mapped to the
   correct JNDI name of the JMS connection factory resource registered with the Sun Java System Application
   Server.

   The following resources should be registered with the Sun Java System Application Server:

       a Destination resource with the JNDI name jms/NewMessage and type javax.jms.Queue

       a Connection Factory resource with the JNDI name jms/NewMessageFactory and type
       javax.jms.QueueConnectionFactory



                                                                                              Send Us Your Feedback


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

  Introduction to Java EE 5 Technology

  Java Persistence in the Java EE 5 Platform

  Comparing Java EE 5 Platform and J2EE 1.4 Platform

  Java EE Applications Learning Trail

You can find more information about using EJB 3.0 Enterprise Beans in the Java EE 5 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.




                                                                                                      Bookmark this page




Shop    SiteMap      About Us   Contact   Legal                                                      By use of this website, you agree to the NetBeans Policies and Terms of Use

More Related Content

What's hot (19)

PDF
Lab 5b) create a java server faces application
techbed
 
PPT
Java J2EE
Sandeep Rawat
 
PDF
Lab 4) working with databases
techbed
 
PPTX
Chapter2 j2ee
Jafar Nesargi
 
PDF
Building Enterprise Application with J2EE
Calance
 
PPS
Dacj 4 1-a
Niit Care
 
PPTX
Spring framework Introduction
Anuj Singh Rajput
 
PDF
J2EE Introduction
Patroklos Papapetrou (Pat)
 
PDF
Part 6 debugging and testing java applications
techbed
 
PPS
Vb net xp_10
Niit Care
 
PPT
Spring ppt
Mumbai Academisc
 
PPT
7) packaging and deployment
techbed
 
PPT
J2ee
Prince Soni
 
DOC
Next-Generation Enterprise Application Development with SpringSource dm Serve...
Aditya Jha
 
DOCX
Brouchure
IIDS NGL
 
DOCX
Core java report
Sumit Jain
 
DOC
Java Interview Questions
anil_kumar132001
 
PDF
Hardware Networking
Pratima Parida
 
Lab 5b) create a java server faces application
techbed
 
Java J2EE
Sandeep Rawat
 
Lab 4) working with databases
techbed
 
Chapter2 j2ee
Jafar Nesargi
 
Building Enterprise Application with J2EE
Calance
 
Dacj 4 1-a
Niit Care
 
Spring framework Introduction
Anuj Singh Rajput
 
J2EE Introduction
Patroklos Papapetrou (Pat)
 
Part 6 debugging and testing java applications
techbed
 
Vb net xp_10
Niit Care
 
Spring ppt
Mumbai Academisc
 
7) packaging and deployment
techbed
 
Next-Generation Enterprise Application Development with SpringSource dm Serve...
Aditya Jha
 
Brouchure
IIDS NGL
 
Core java report
Sumit Jain
 
Java Interview Questions
anil_kumar132001
 
Hardware Networking
Pratima Parida
 

Viewers also liked (7)

PDF
Newsletter5
applied_development
 
PDF
Newsletter4
applied_development
 
PPTX
Jaxon- Cure for EB
Debbie Reddinger
 
PDF
Case study bzwbk
MonikaRadomska
 
PPTX
airtel Presentation
shankar san
 
Newsletter5
applied_development
 
Newsletter4
applied_development
 
Jaxon- Cure for EB
Debbie Reddinger
 
Case study bzwbk
MonikaRadomska
 
airtel Presentation
shankar san
 
Ad

Similar to Tutorial for netbeans (20)

PDF
Ejb notes
Mumbai Academisc
 
PDF
Free EJB Tutorial | VirtualNuggets
Virtual Nuggets
 
PDF
EJ NOV-18 (Sol) (E-next.in).pdf
SPAMVEDANT
 
PDF
Part 3 web development
techbed
 
PDF
Spring Framework Tutorial | VirtualNuggets
Virtual Nuggets
 
PPTX
Introduction to vb.net
Jaya Kumari
 
PDF
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Amit Singh
 
PPT
ADVANCED JAVA MODULE I & II.ppt
rani marri
 
PDF
Jsf tutorial
Edress Oryakhail
 
DOCX
Spring notes
Rajeev Uppala
 
PDF
JEE Programming - 02 The Containers
Danairat Thanabodithammachari
 
PDF
Java tutorial
shalsmart12
 
PDF
Building richwebapplicationsusingasp
Giovanni Javier Jimenez Cadena
 
ODP
Net Beans
marx wang
 
ODP
Net Beans
marx wang
 
PDF
Part 5 running java applications
techbed
 
PPTX
Introduction to ejb and struts framework
s4al_com
 
PDF
Java server face tutorial
Abderrahman Bachiri Taoufiq
 
PPT
Aravind vinnakota ejb_architecture
tayab4687
 
Ejb notes
Mumbai Academisc
 
Free EJB Tutorial | VirtualNuggets
Virtual Nuggets
 
EJ NOV-18 (Sol) (E-next.in).pdf
SPAMVEDANT
 
Part 3 web development
techbed
 
Spring Framework Tutorial | VirtualNuggets
Virtual Nuggets
 
Introduction to vb.net
Jaya Kumari
 
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Amit Singh
 
ADVANCED JAVA MODULE I & II.ppt
rani marri
 
Jsf tutorial
Edress Oryakhail
 
Spring notes
Rajeev Uppala
 
JEE Programming - 02 The Containers
Danairat Thanabodithammachari
 
Java tutorial
shalsmart12
 
Building richwebapplicationsusingasp
Giovanni Javier Jimenez Cadena
 
Net Beans
marx wang
 
Net Beans
marx wang
 
Part 5 running java applications
techbed
 
Introduction to ejb and struts framework
s4al_com
 
Java server face tutorial
Abderrahman Bachiri Taoufiq
 
Aravind vinnakota ejb_architecture
tayab4687
 
Ad

Tutorial for netbeans

  • 1. Choose page language Search: HOME / Docs & Support / NetBeans 5.5 EJB 3.0 Enterprise Beans Learning Trails This document takes you through the basics of developing an enterprise application using EJB 3.0 Basic Java Programming technology which is part of the Java EE 5 platform. This document shows how the EJB 3.0 Java GUIs and Project Matisse technology can simplify the process of developing enterprise applications. This document uses the Web Applications NetBeans IDE 5.5 Release. Java EE Applications Expected duration: 30 minutes Mobile Applications SOA Applications and UML Prerequisites NetBeans Modules and Rich- This document assumes you have some basic knowledge of, or programming experience with, Client Applications the following technologies: Java Programming Docs for Packs NetBeans IDE Mobility Pack Visual Web Pack Software Needed for the Tutorial Enterprise Pack For this tutorial you need to have the following software installed on your computer: C/C++ Pack NetBeans IDE 5.5 (download). Profiler Java Standard Development Kit (JDK) version 5.0 or version 6.0 (download) UML Module Sun Java System Application Server, Platform Edition 9 (download) For this tutorial you need to register a local instance of Sun Java System Application Server Additional Resources with the IDE. FAQs Sample Applications Tutorial Exercises Support Setting Up the Enterprise Application Project Training Coding the EJB Module NetBeans 5.0 Docs Coding the Web Module NetBeans 6.0 Preview Docs Contribute Documentation! Running the Project Troubleshooting Setting Up the Enterprise Application Project The goal of this exercise is to create the NewsApp enterprise application project containing an EJB module and a web module. The NewsApp application uses a message-driven bean to receive and process messages sent to the queue by a servlet. The application uses servlets to send messages to the message-driven bean and to display messages. Creating an Enterprise Application 1. Choose File > New Project (Ctrl-Shift-N) from the main menu. 2. Select Enterprise Application from the Enterprise category and click Next. 3. Name the project NewsApp and set the server to Sun Java System Application Server. 4. Set the J2EE Version to Java EE 5, and select Create EJB Module and Create Web Application Module, if unselected. 5. Click Finish. Summary In this exercise we created a Java EE 5 enterprise application containing an EJB module and a web module. Coding the EJB Module In this exercise we will create the objects in the EJB module. We will create an entity class, a message-driven bean and a session facade. We also will create a persistence unit to provide the container with information for managing our entities, and the Java Message Service (JMS) resources that our message-driven bean will use. Creating a Persistence Unit First we create a persistence unit that defines the data source and entity manager used in our application. 1. Right-click the EJB module and choose New > File/Folder. 2. From the Persistence category, select Persistence Unit and click Next.
  • 2. 3. Keep the default Persistence Unit Name. 4. For the Persistence Provider, choose TopLink (default). 5. For the Data Source, choose the default data source jdbc/sample. 6. Check that the persistence unit is using the Java Transaction API and that the Table Generation Strategy is set to Create so that the tables based on our entity classes are created when the application is deployed. 7. Click Finish. When you click Finish, the IDE creates persistence.xml and opens it in the Source Editor in Design view. Close persistence.xml. Creating the NewsEntity Entity Class In this exercise we will create the NewsEntity entity class. An entity class is a simple Java class. When you create the entity class, the IDE adds the @Entity annotation to define the class as an entity class. After we create the class, we will create fields in the class to represent the data that we want in our table. Each entity class must have a primary key. When you create the entity class, the IDE adds the @Id annotation to declare which field to use as the primary key. The IDE also adds the @Generated annotation to specify the key generation strategy for the primary Id. To create the NewsEntity class, do the following: 1. Right-click the EJB module in the Project window and choose New > File/Folder to open the New File wizard. 2. From the Persistence category, select Entity Class and click Next. 3. Type NewsEntity for the class name, 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, do the following: 1. Add the following field declarations to the class: String title; String body; 2. Right-click in the Source Editor and choose Refactor > Encapsulate Fields to generate getters and setters for each of the fields. In the Encapsulate Fields dialog box, make sure that getter and setter checkboxes are selected for the fields id, title and body. 3. Click Next in the Encapsulate Fields dialog box and then click Do Refactoring in the Refactoring tab of the Output window. The IDE adds the getter and setter methods for the fields and changes the visibility of the fields to private. 4. Save your changes to the file. In the next step we will create the NewMessage message-driven bean. Creating the NewMessage Message-Driven Bean Now we will create the NewMessage message-driven bean in our EJB module. We will use the New Message-Driven Bean wizard to create the bean and the necessary JMS resources. To create the NewMessage message-driven bean, do the following:
  • 3. 1. Right-click the EJB module in the Projects window and choose New > File/Folder to open the New File wizard. 2. From the Enterprise category, select Message-Driven Beans and click Next. 3. Type NewMessage for the class name. 4. Select ejb from the Package drop-down list. 5. Select Queue as the Destination Type and click Finish. When you click Finish, the new message-driven bean class NewMessage.java opens in the Source Editor. You can see that the class has the following annotation: @MessageDriven(mappedName = "jms/NewMessage") This annotation tells the container that the component is a message-driven bean and the JMS resource used by the bean. When the IDE generates the class, the Mapped Name of the resource (jms/NewMessage) is derived from the name of the class (NewMessage.java). The JMS resource is mapped to the JNDI name of the destination from which the bean receives messages. The New Message-Driven Bean wizard has already created the JMS resources for us. The EJB 3.0 API enables us to look up objects in the JNDI namespace from within the bean class so that we do not need to configure deployment descriptors to specify the JMS resources. The EJB 3.0 specifications allow us to use annotations to introduce resources directly into a class. We will now use annotations to introduce the MessageDrivenContext resource into our class, and then inject the PersistenceContext resource which will be used by the EntityManager API to manage the persistent entity instances. We will add the annotations to the class in the Source Editor. 1. Inject the MessageDrivenContext resource into the class by adding the following annotated field (in bold) to the class: public class NewMessage implements MessageListener { @Resource private MessageDrivenContext mdc; 2. Introduce the entity manager into the class by right-clicking in the code and selecting Persistence > Use Entity Manager from the pop-up menu. This adds the following annotation to your source code: @PersistenceContext private EntityManager em; and generates the following method in your code: public void persist(Object object) { // TODO: // em.persist(object); } 3. Modify the persist method to change the name to save. The method should look like the following: public void save(Object object) { em.persist(object); } 4. Modify the onMessage method by adding the following to the body: 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(); } 5. Press Alt-Shift-F to generate any necessary import statements. When generating the import statements,
  • 4. we want to make sure we import the jms and javax.annotation.Resource; libraries. 6. Save the file. Creating the Session Bean Next we create a session facade for the NewsEntity entity class. To create the session facade, do the following: 1. Right-click the EJB module and choose New > File/Folder. 2. From the Persistence category, select Session Beans for Entity Classes and click Next. 3. From the list of available entity classes, select NewsEntity and click Add and then click Next. 4. Check that the Package is set to ejb and that a local interface will be created. 5. Click Finish. When you click Finish, the session facade class NewsEntityFacade.java is created and opens in the Source Editor. The IDE also creates the local interface NewsEntityFacadeLocal.java. EJB 3.0 technology simplifies the creation of session beans by reducing the amount of required code. You can see that the annotation @Stateless is used to declare the class as a stateless session bean component and that the class no longer needs a statement implementing javax.ejb.SessionBean. The code is also much cleaner because with EJB 3.0 technology the business methods no longer need to have code declaring they throw checked exceptions. You can see that the PersistenceContext resource was injected directly into the session bean component when we created the session facade. Summary In this exercise, we coded an entity class and a message-driven bean in the EJB module. We then created a session facade for the entity class. We also created the JMS resources that will be used by our application. Coding the Web Module We will now create the servlets ListNews and PostMessage in our web module. These servlets will be used to read and add messages. Creating the ListNews Servlet In this exercise we will create a simple servlet for displaying our data. We will use annotations to call our entity bean from our servlet. 1. Right-click the web module project and choose New > Servlet. 2. Type ListNews for the Class Name. 3. Enter web for the Package name and click Finish. When you click Finish, the class ListNews.java opens in the Source Editor. In the Source Editor, do the following: 1. Right-click in the source code and select Enterprise Resources > Call Enterprise Bean. 2. In the Call Enterprise Bean dialog box, select NewsEntityFacade and click OK. When you click OK, the entity bean resource is injected in the servlet using the @EJB annotation. 3. 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>"); 4. Press Alt-Shift-F to generate any necessary import statements for the class. When generating the import statements, we want to import classes from the util package. 5. Save the changes to the file. Creating the PostMessage Servlet In this exercise we will create the PostMessage servlet that will be used to post messages. We will use
  • 5. annotations to inject the JMS resources we created directly into the servlet, specifying the variable name and the name to which it is mapped. We 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. Enter web for the Package name and click Finish. When you click Finish, the class PostMessage.java opens in the Source Editor. In the Source Editor, do the following: 1. Use annotations to inject the ConnectionFactory and Queue resources by adding the following field declarations (in bold): public class PostMessage extends HttpServlet { @Resource(mappedName="jms/NewMessageFactory") private ConnectionFactory connectionFactory; @Resource(mappedName="jms/NewMessage") private Queue queue; 2. We now add the code to send the JMS messages by adding the following code in bold 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(); } } PrintWriter out = response.getWriter(); 3. We now uncomment the code to print the HTML and add the web form for adding a message. Add the following lines in bold to the processRequest method out.println("Servlet PostMessage at " + request.getContextPath() + "</h1>"); // Add the following code to add 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>"); 4. Press Alt-Shift-F to generate any necessary import statements for the class. Note: When selecting the which libraries to import for Connection, ConnectionFactory, Session and Queue, make sure you import the java.jms libraries.
  • 6. 5. Save your changes to the file. Running the Project We can now run our project. When we run the project, we want our browser to open to the page with the ListNews servlet. We do this by specifying the URL in the Properties dialog box for our Enterprise Application. The URL is relative to the context path for our application. After we enter the relative URL, we can build, deploy and run our application from the Projects window. To set the relative URL and run our application, do the following: 1. In the Projects window, right-click the NewsApp enterprise application node and select Properties in the pop- up menu. 2. Select Run in the Categories pane. 3. In the Relative URL textfield, type /ListNews. 4. Click OK. 5. In the Projects window, right click the NewsApp enterprise application node and choose Run Project. When you run the project, the ListNews servlet opens in your browser and displays a list of the messages in the database. When you first run the project, the database is empty, but you can click Add Message to add a message. 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. Troubleshooting The following are some of the problems you may encounter when creating your project. Problem with JMS Resources When using the wizard to create JMS resources, you may see the following server error message in the output window: [com.sun.enterprise.connectors.ConnectorRuntimeException: JMS resource not created : jms/Queue] This message could indicate that the JMS resource was not created or was not registered with the application server. You can use the Admin Console of the Sun Java System Application Server to check, create and edit JMS resources. To open the Admin Console, do the following: 1. Confirm that the Sun Java System Application Server is running by expanding the Servers node in the Runtime of the IDE. A small green arrow next to the Sun Java System Application Server node indicates the server is running. 2. Right-click the Sun Java System Application Server node and choose View Admin Console to open the login window in your browser.
  • 7. 3. Log in to the Sun Java System Application Server. The default user name and password are admin and adminadmin. 4. In the Admin Console in your browser, expand the Resources node and JMS Resources node in the left frame. 5. Click on the Connection Factories and Destination Resources links in the left frame to check if the resources are registered with the server and if necessary modify the resources. If the resources do not exist, you can create them in the Admin Console. You need to make sure that the JMS connection factory resource in the PostMessage servlet is mapped to the correct JNDI name of the JMS connection factory resource registered with the Sun Java System Application Server. The following resources should be registered with the Sun Java System Application Server: a Destination resource with the JNDI name jms/NewMessage and type javax.jms.Queue a Connection Factory resource with the JNDI name jms/NewMessageFactory and type javax.jms.QueueConnectionFactory Send Us Your Feedback Next Steps For more information about using NetBeans IDE 5.5 to develop Java EE applications, see the following resources: Introduction to Java EE 5 Technology Java Persistence in the Java EE 5 Platform Comparing Java EE 5 Platform and J2EE 1.4 Platform Java EE Applications Learning Trail You can find more information about using EJB 3.0 Enterprise Beans in the Java EE 5 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. Bookmark this page Shop SiteMap About Us Contact Legal By use of this website, you agree to the NetBeans Policies and Terms of Use