This document introduces the basic knowledge about developing enterprise applications using the EJB 3.0 technology (as part of the Java ee 5 platform, it also explains how the EJB 3.0 technology simplifies the development process of enterprise applications. This document uses netbeans ide 5.5 beta.
Note that this release version is Beta. To obtain the latest full release version, go to the netbeans download page and download netbeans ide 5.0.
Estimated time: 30 minutes
Prerequisites
This document assumes that you have basic knowledge or programming experience in the following technologies:
- Java programming
- Netbeans ide
Software required for this tutorial
Before learning this tutorial, you must install the following software on your computer:
- Netbeans ide 5.5 beta (download)
- Java standard development kit (JDK) version 5.0 (download)
- Sun Java System Application Server Platform edition 9 (download)
Before learning this tutorial, you must register a local Sun Java System Application Server instance in the IDE.
Tutorial exercises
- Create an enterprise application project
- Encode the EJB Module
- Code the web module
- Run the project
Create an enterprise application project
This exercise aims to create a newsapp enterprise application project that contains an EJB module and a web module. The newsapp application uses the message-driven bean to receive and process messages sent from servlet to the queue. The application uses servlet to send messages to the message-driven bean and display messages.
Create an enterprise application
- Select "file"> "new project" (CTRL-shift-N ). Select "enterprise application" from the "Enterprise" category ".
- Name the project newsapp and set the server to "Sun Java System Application Server ".
- Set the J2EE version to "Java ee 5", and then select "create EJB module" and "Create web application module" (if not selected ).
- Click "finish ".
Summary
In this exercise, we created a Java ee 5 enterprise application that contains an EJB module and a web module.
Encode the EJB Module
In this exercise, we will create an object in the EJB module. We will create entity classes, message-driven beans, and Session Facade. We will also create a persistent unit to provide the container with information for Object Management and the Java Message Service (JMS) resources that the message-driven bean will use.
Create a persistent Unit
First, we will create a persistent unit that defines the data source and Entity Manager used in the application.
- Right-click the EJB module and choose "New"> "file/folder ".
- From the "persistence" category, select "persistence unit" and click "Next ".
- Retain the default persistent unit name.
- For "persistence provider", useToplink (default).
- For "Data Source", use the default data sourceJDBC/sample.
- Make sure that the "use Java transaction APIs" check box is selected for the persistence unit, and set "Table Generation Strategy" to "CREATE ", in this way, you can create a table based on the object class when deploying an application.
- Click "finish ".
After you click "finish", IDE will createPersistence. xmlAnd open it in the source code editor.
Create NewsentityEntity class
In this exercise, we will createNewsentityEntity class. An object class is a simple Java class. When you create an object class, IDE adds@ EntityAnnotation to define this class as an entity class. After a class is created, fields in the class are created to represent the data required in the table.
Each entity class must have a primary key. When you create an object class, IDE adds@ IDAnnotation to declare the field to be used as the primary key. In addition, the IDE will add@ GeneratedAnnotation to specify the key generation policy of the primary ID.
To createNewsentityClass, perform the following operations:
- In the "project" window, right-click the EJB module and choose "New"> "file/folder" to open the "new file" Wizard.
- Select "entity class" from "persistence" category, and click "Next ".
- TypeNewsentityAs the class name, typeEJBAs the package name, and keep "primary key type"Long. Click "finish ".
After you click "finish", the object class is opened in the source code editor.Newsentity. Java. In the source code editor, perform the following operations:
- Add the following field declaration to the class:
String title;
String body;
- Select "refactor"> "encapsulate fields" to generate the getter and setter methods for each field. In the "encapsulate fields" dialog box, make sure that the field is selected.ID,TitleAndBodyThe getter and setter check boxes.
- Click "Next" in the "encapsulate fields" dialog box, and then click "Do refactoring" in the "refactoring" tab of the "output" window ". IDE will add the getter and setter methods for each field, and change the field visibilityPrivate.
- Save the changes made to the file.
In the next step, we will createNewmessageMessage-driven bean.
Create NewmessageMessage-driven Bean
Now we will createNewmessageMessage-driven bean. We will use the "New message-driven Bean" Wizard to create a bean. In this wizard, enterJMS/newmessageTo inject resources into the class.
To createNewmessageMessage-driven Bean:
- In the "project" window, right-click the EJB module and choose "New"> "file/folder" to open the "new file" Wizard.
- From the "Enterprise" category, select "message-driven beans" and click "Next ".
- TypeNewmessageAs the class name.
- Select from the package drop-down listEJB.
- In the mapped Name field, enterJMS/newmessageAnd then click "finish ".
After you click "finish", the newly created message-driven Bean class will be opened in the source code editor.Newmessage. Java. You can see that the class has the following annotations:
@MessageDriven(mappedName = "jms/Queue")
This annotation indicates to the container that the component is a message-driven bean and the bean uses JMS resources. The JMS resource is mapped to the JNDI name of the target, and the bean receives messages from the target. The "New message-driven Bean" Wizard has created JMS resources for us. Through the EJB 3.0 API, we can find the objects in the JNDI namespace from the Bean class, so we do not need to configure the deployment descriptor to specify the JMS resource.
With the EJB 3.0 software, we can use annotations to directly introduce resources to classes. Now, we are going to use the annotationMessagedrivencontextIntroduce the resource into the class, and then injectPersistencecontextThe entitymanager API uses this resource to manage persistent entity instances. Add annotation to the class in the source code editor.
- By adding the marked field to the field declaration listMessagedrivencontextInject resources into the class:
@Resource
private MessageDrivenContext mdc;
- Right-click the code and select "persistence"> "use Entity Manager" from the pop-up menu to introduce the Entity Manager to the class.
This will add the following annotations to the source code: @PersistenceContext
private EntityManager em;
And generate the following method in the Code:
public void changeMyName(Object object) {
// TODO:
// em.persist(object);
}
- Modify as follows:ChangemynameMethod:
public void save(Object object) {
em.persist(object);
}
- Add the following code to the subject to modifyOnmessageMethod:
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();
}
- Press Alt-shift-F to generate all necessary import statements. When generating the Import Statement, we want to importJMSLibrary.
- Save the file.
Create Session Bean
Next, we willNewsentityThe entity class creates a Session Facade. To create a Session Facade, perform the following operations:
- Right-click the EJB module and choose "New"> "file/folder ".
- Select "Session Facade" from the "persistence" category and click "Next ".
- Select newsentity from the list of available object classes, click Add, and then click Next ".
- Check whether the source code package is setEJBAnd create a local interface.
- Click "finish ".
After you click "finish", the Session Facade class will be created.Newsentityfacade. JavaAnd open it in the source code editor. IDE will also create a local InterfaceNewsentityfacadelocal. Java.
The EJB 3.0 technology simplifies the creation of session beans by reducing the amount of code required. You can see that the Annotation@ StatelessDeclares a class as a stateless Session Bean component, and this class no longer needs to be implementedJavax. EJB. sessionbean. In addition, the Code is more concise, because by using EJB 3.0 technology, business methods no longer need to use code to declare that they throw the checked exception.
You will see that when you create a Session Facade,PersistencecontextResources have been directly injected into the session bean component.
Summary
In this exercise, we have encoded the entity class and message-driven bean in the EJB module, and created a Session Facade for the entity class. In addition, we have created the JMS resources used by the application.
Code the web module
Now, we will create a servlet in the web moduleListnewsAndPostmessage. These servlets are used to read and add messages.
Create ListnewsServlet
In this exercise, we will create a simple servlet for displaying data. We will use annotation to call the Entity Bean from the servlet.
- Right-click the web module project and choose "New"> "servlet ".
- TypeListnewsAs the class name.
- InputWebAs the package name, and then click "finish ".
After you click "finish", the class is opened in the source code editor.Listnews. Java. In the source code editor, perform the following operations:
- In the source code, right-click and select "Enterprise Resources"> "call enterprise Bean ".
- In the "call enterprise Bean" dialog box, select "newsentityfacade" and click "OK ". After you click "OK ",@ EJBInject Entity Bean resources in servlet.
- Uncomment the code and add the following code lines in boldProcessrequestTo modify the method:
out.println("
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>");
- Press Alt-shift-F to generate all necessary import statements for the class. When generating the Import Statement, we wantUtilPackage import class.
- Save the changes made to the file.
Create PostmessageServlet
In this exercise, we will createPostmessageServlet. The annotation is used to directly inject the created JMS resource into the servlet and specify the variable name and the name mapped to it. Then, add the code used to send the JMS message and the code used to add the message to the HTML form.
- Right-click the web module project and choose "New"> "servlet ".
- TypePostmessageAs the class name.
- InputWebAs the package name, and then click "finish ".
After you click "finish", the class is opened in the source code editor.Postmessage. Java. In the source code editor, perform the following operations:
- Add the following field declaration and use annotation for injection.ConnectionfactoryAndQueueResource:
public class PostMessage extends HttpServlet {
@Resource(mappedName="jms/NewMessageFactory")
private ConnectionFactory connectionFactory;
@Resource(mappedName="jms/NewMessage")
private Queue queue;
- Now, add the following code in boldProcessrequestMethod, add the code used to send the JMS message:
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);
response.sendRedirect("ListNews");
} catch (JMSException ex) {
ex.printStackTrace();
}
}
PrintWriter out = response.getWriter();
- Now, the output HTML code is uncommented and a web form is added for adding messages. Add the following code lines in boldProcessrequestMethod:
out.println("Servlet PostMessage at " + request.getContextPath() + " ");
// 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>");
- Press Alt-shift-F to generate all necessary import statements for the class. In the selectConnection,Connectionfactory,SessionAndQueueThe Import StatementJava. JMSLibrary.
- Save the changes made to the file.
Run the project
Now you can run the project. When running the project, we want the browser to openListnewsServlet page. You can specify the URL of the page in the Enterprise Application Properties dialog box. This URL is the relative URL of the context path of the application. After entering the relative URL, you can generate, deploy, and run the application from the project window.
To set the relative URL and run the application, perform the following operations:
- In the projects window, right-click the newsapp enterprise application node and select Properties from the pop-up menu ".
- In the "categories" pane, select "run ".
- In the "relative URL" text field, type/listnews.
- Click "OK ".
- In the projects window, right-click the "newsapp" enterprise application node and select "run project ".
When running the project, it will be opened in the browserListnewsServlet, which is used to display the list of messages in the database. If this is the first time you run the project, the database is empty, but you can click "add message" to add messages.
When you usePostmessageWhen adding a message to a servlet, the message is sent to the message-driven bean to be written to persistent storage and calledListnewsServlet to display messages in the database. ByListnewsThe message list in the retrieved database usually does not contain new messages, because the message service is asynchronous.
Note: I am not liable for any of the above content from the Internet.
Article transferred from: http://blog.chinaunix.net/u/14788/showart_215066.html