Beruflich Dokumente
Kultur Dokumente
print=yes
The application contains an EJB module and a web module. The EJB module contains an entity class, a session facade for the
entity class and a message-driven bean. The web module contains servlets for displaying and posting messages and a singleton
session bean that counts the number of users in the session.
Before starting this tutorial you may want to familiarize yourself with the following document.
Tutorial Exercises
Troubleshooting
To follow this tutorial, you need the following software and resources.
Notes.
NetBeans IDE 6.9 and the GlassFish server 3.0.1 require Java Development Kit (JDK) 6.
If you are using GlassFish v2 or an older version of NetBeans IDE, see Getting Started with Java EE Applications.
Prerequisites
This document assumes you have some basic knowledge of, or programming experience with, the following technologies:
Java Programming
NetBeans IDE
1 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
The structure of the NewsApp application generally corresponds to the following tiers.
Web Tier. The Web Tier contains the presentation logic of the application and runs on a Java EE server. In the NewsApp
application, the Web Tier is represented by the web module and contains servlets that access the business logic in the EJB
module.
Business Tier. Business Tier applications also run on Java EE servers and contain the business logic of the application. In
the NewsApp application, the Business Tier is represented by the EJB module. The EJB module contains the code that
handles requests from the Web Tier clients and manages transactions and how objects are persisted to the database.
EIS Tier. The EIS Tier is the persistent storage layer of the application. In the NewsApp application, this tier is
represented by the database where the messages are stored.
When you build an enterprise application in the IDE, the EJB and web application modules are packaged in an EAR archive that
is then deployed to the server. The application is then typically accessed from the Client Tier. The Client Tier is the environment
where the client is run and is often a web browser on a user's local system.
Note. In the example in this tutorial you will use a single machine to host the Java EE server, the database and view the
web pages. In large enterprise applications, the different tiers are often distributed across multiple machines. The Web Tier
and Business Tier applications are often deployed to Java EE servers that are hosted on different machines.
For more details about the structure of Java EE enterprise applications, see the chapter on Distributed Multitiered
Applications in the Java EE 6 Tutorial, Part I.
1. Choose File > New Project (Ctrl-Shift-N) from the main menu.
2. Select Enterprise Application from the Java EE category and click Next.
5. Set the server to GlassFish Server 3 and set the Java EE Version to Java EE 6.
6. Select Create EJB Module and Create Web Application Module, if unselected. Click Finish.
2 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
When you click Finish, the IDE creates three projects: NewsApp, NewsApp-ejb and NewsApp war. If you expand the NewsApp
node in the Projects window, you can see that the enterprise application project does not contain any sources. All the sources will
be contained in the two modules that the wizard created and which are listed under the Java EE Modules node.
The enterprise application project only contains configuration details about the application in a deployment descriptor file
sun-application.xml. Deployment descriptor files are not required when you create a Java EE enterprise application that is
deployed to GlassFish Server 3.
3 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
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 @GeneratedValue annotation and specifies the key generation
strategy for the primary Id.
1. Right-click the EJB module in the Projects window and choose New > Other to open the New File wizard.
2. From the Persistence category, select Entity Class and click Next.
5. Leave the Primary Key Type as Long in the New Entity Class wizard.
6. Click Create Persistence Unit to open the Create Persistence Unit dialog box.
9. For the Data Source, choose a data source (for example, select jdbc/sample if you want to use JavaDB).
10. 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 your entity classes are created when the application is deployed.
When you click Finish, the IDE creates persistence.xml and the entity class NewsEntity.java. The IDE opens
NewsEntity.java in the Source Editor.
4 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
3. Select Getter and Setter in the popup menu to open the Generate Getters and Setters dialog box.
4. Select the body and title fields in the dialog box. Click Generate.
When you click Generate, the IDE adds getter and setter methods for the fields.
For more details about entity classes, see the chapter Introduction to the Java Persistence API in the Java EE 6 Tutorial,
Part I.
1. Right-click the EJB module in the Projects window and choose New > Other to open the New File wizard.
5. Click the Add button next to the Project Destination field to open the Add Message Destination dialog box.
6. In the Add Message Destination dialog box, type jms/NewMessage and select Queue for the destination type. Click
OK.
5 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
When you click Finish, the bean class NewMessage.java opens in the Source Editor. You can see that the IDE added the
@MessageDriven annotation and configuration properties to the class.
The @MessageDriven annotation tells the container that the component is a message-driven bean and specifies 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 also adds the information for the JMS
resources to sun-resources.xml. You do not need to configure deployment descriptors to specify the JMS resources. If you
use the Run action in the IDE to deploy the application to GlassFish, the JMS resources are created on the server on
deployment.
The EJB specifications allow you to use annotations to introduce resources directly into a class. You will now use annotations
to introduce the MessageDrivenContext resource into your class, and then inject the PersistenceContext resource which
will be used by the EntityManager API to manage the persistent entity instances. You 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:
@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.
The IDE adds the following @PersistenceContext annotation to your source code.
6 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
@PersistenceContext(unitName = "NewsApp-ejbPU")
private EntityManager em;
3. Modify the persist method to change the name to save. The method should look like the following:
4. Modify the onMessage method by adding the following code (in bold) to the body of the method.
5. Press Ctrl-Shift-I to generate any necessary import statements. Save your changes.
Note. When generating the import statements, you want to make sure to import the jms and
javax.annotation.Resource libraries.
For more details about message-driven beans, see the chapter What is a Message-Driven Bean? in the Java EE 6
Tutorial, Part I.
2. From the Persistence category, select Session Beans for Entity Classes. Click Next.
3. Select ejb.NewsEntity from the list of available entity classes and click Add to move the classs to the Selected
Entity Classes pane. Click Next.
7 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
When you click Finish, the session facade NewsEntityFacade.java is created and opens in the Source Editor. The IDE adds
the @Stateless annotation that declares the class is a stateless session bean. The IDE also adds the PersistenceContext
annotation to inject the resource directly into the session bean component.
Note. Remote interfaces are still required if the beans will be accessed by remote clients.
For more information about session beans, see the chapter What is a Session Bean? in the Java EE 6 Tutorial, Part I.
In this section you will also create a singleton session bean in the web module that will count the number of users that are
currently in the session. The EJB 3.1 specification enables you to create enterprise beans in web applications. Prior to EJB 3.1, all
enterprise beans had to be in EJB modules.
After the singleton session bean is instantiated it exists for the lifecycle of the application. As its name implies, there can only
be a single instance of a singleton session bean in the application. Like stateless session beans, singleton session beans can
have multiple clients.
1. Right-click the Web module and choose New > Other to open the New File wizard.
8 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
When you click Finish, the IDE creates the singleton session bean class and opens the class in the editor. You can see that
the IDE added the annotation @Singleton to the class to declare a singleton session bean. The wizard also annotated the
class with @LocalBean.
@Singleton
@LocalBean
public class SessionManagerBean {
@Singleton
@LocalBean
@WebListener
public class SessionManagerBean implements HttpSessionListener{
The @WebListener annotation is part of the Servlet 3.0 API and enables you to implement a listener directly in your
code.
When you implement HttpSessionListener, the IDE displays a warning in the margin.
2. Click the warning badge in the left margin and choose "Implement all abstract methods".
9 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
3. Add the static field counter and set the initial value to 0.
@LocalBean
@WebListener
public class SessionManagerBean implements HttpSessionListener{
private static int counter = 0;
4. Modify the generated bodies of the sessionCreated and sessionDestroyed methods to increase the value of a field
when a new session starts and to decrease the value when a session finishes. The value will be stored in the field
counter.
5. Add the following method that returns the current value of counter.
You will call this method from a servlet to display the current number of users/open sessions.
The code for the session bean should now look like the following.
10 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
@Singleton
@LocalBean
@WebListener
public class SessionManagerBean implements HttpSessionListener {
private static int counter = 0;
For more details about singleton session beans, see the chapter What is a Session Bean? in the Java EE 6 Tutorial, Part
I.
1. Right-click the web module project and choose New > Servlet.
When you click Finish, the class ListNews.java opens in the Source Editor. In the source editor, perform the following
steps.
1. Right-click in the source editor and choose Insert Code and then select Call Enterprise Bean.
2. In the Call Enterprise Bean dialog box, expand the NewsApp-ejb node and select NewsEntityFacade. Click OK.
The IDE adds the @EJB annotation to inject the enterprise bean.
3. Use the Call Enterprise Bean dialog box again to inject the SessionManagerBean under the NewsApp-war node.
In your code you will see the following annotations that inject the two enterprise beans.
@EJB
private SessionManagerBean sessionManagerBean;
@EJB
private NewsEntityFacade newsEntityFacade;
You can also see that the @WebServlet annotation is used to declare the class a servlet and to specify the servlet
name. The @WebServlet annotation is part of the Servlet 3.0 API introduced in the Java EE 6 specification. You can
identify servlets using the annotation instead of in the web.xml deployment descriptor. The NewsApp application does
11 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
4. In the processRequest method, add the following code (in bold) to return the current session or create a new one.
5. Uncomment the code in the processRequest method and add the following code (in bold) to print the messages and
add a link to the PostMessage servlet:
out.println("</body>");
6. Add the following code (in bold) to retrieve and print the number of users/open sessions.
out.println("<br><br>");
out.println(sessionManagerBean.getActiveSessionsCount() + " user(s) reading the news.");
out.println("</body>");
7. Press Ctrl-Shift-I to generate any necessary import statements for the class. When generating the import statements,
you want to import the java.util libraries.
1. Right-click the web module project and choose New > Servlet.
When you click Finish, the class PostMessage.java opens in the source editor. In the source editor, perform the following
steps.
1. Use annotations to inject the ConnectionFactory and Queue resources by adding the following field declarations (in
bold):
12 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
@WebServlet(name="PostMessage", urlPatterns={"/PostMessage"})
public class PostMessage extends HttpServlet {
@Resource(mappedName="jms/NewMessageFactory")
private ConnectionFactory connectionFactory;
@Resource(mappedName="jms/NewMessage")
private Queue queue;
2. You 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");
message.setObject(e);
messageProducer.send(message);
messageProducer.close();
connection.close();
response.sendRedirect("ListNews");
3. 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
13 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
out.println("</body>");
4. Press Ctrl-Shift-I 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 javax.jms libraries.
To set the relative URL and run the application, do the following:
1. In the Projects window, right-click the NewsApp enterprise application node and select Properties in the pop-up menu.
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.
14 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
You can download the solution to this tutorial as a project in the following ways.
Checkout the project sources from the NetBeans Samples by performing the following steps:
1. Choose Team > Subversion > Checkout from the main menu.
5. Specify the Local Folder for the sources (the local folder must be empty).
6. Click Finish.
When you click Finish, the IDE initializes the local folder as a Subversion repository and checks out the project
sources.
7. Click Open Project in the dialog that appears when checkout is complete.
Notes.
You need a Subversion client to checkout the sources from Kenai. For more about installing Subversion, see the
section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.
Troubleshooting
The following are some of the problems you may encounter when creating your project.
[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 application server to check, create and edit JMS resources.
1. Confirm that the application server is running by expanding the Servers node in the Services window of the IDE. A
small green arrow next to the application server node indicates the server is running.
2. Right-click the application server node and choose View Admin Console to open the login window in your browser.
3. Log in to the 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
15 of 16 11/6/2010 12:14 PM
Creating an Enterprise Application with EJB 3.1 http://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html?print=yes
a Connection Factory resource with the JNDI name jms/NewMessageFactory and type
javax.jms.QueueConnectionFactory
See Also
For more information about using NetBeans IDE to develop Java EE applications, see the following resources:
You can find more information about using EJB 3.1 Enterprise Beans in the Java EE 6 Tutorial.
To send comments and suggestions, get support, and keep informed on the latest developments on the NetBeans IDE Java EE
development features, join the nbj2ee mailing list.
16 of 16 11/6/2010 12:14 PM