Creating JMS application using JSF and CDI beans

In this section, we will see how to create a JMS application using JSF and Component Dependency Injection (CDI) beans. With CDI beans, we can reduce the code that we wrote using JMS APIs, because we can use annotations to inject objects such as the JMS connection factory, queue, and topic. Once we obtain references to these objects, the steps to send or receive data are the same as those discussed in the previous section. Therefore, our examples in this section do not list the entire code. For the complete source code, download the source code for this chapter.

To prepare our project for using JSF, we need to create web.xml and add the JSF servlet definition and mapping in it. Right-click on the project and select the Java EE Tools | Generate Deployment Descriptor Stub option. This creates web.xml in the WebContent/WEB-INF folder. Add the following servlet definition and mapping (within the web-app tag) in web.xml:

  <servlet> 
    <servlet-name>JSFServelt</servlet-name> 
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> 
    <load-on-startup>1</load-on-startup> 
  </servlet> 
 
  <servlet-mapping> 
    <servlet-name>JSFServelt</servlet-name> 
    <url-pattern>*.xhtml</url-pattern> 
  </servlet-mapping> 

For CDI beans to work, we need to create a beans.xml file in the META-INF folder. You will find the META-INF folder under the WebContent folder in the project in Eclipse. Let's create the bean.xml file in META-INF with the following content:

<beans xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

We will now create two CDI beans for the JSF page. The first one is CourseManagedMsgSenderBean. The second one is CourseJSFBean, which will be referenced from the JSF page.

Create the CourseManagedMsgSenderBean class in the packt.jee.eclipse.jms.jsf_bean package with the following content:

package packt.jee.eclipse.jms.jsf_bean;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
//skipped other imports

@Named("courseMessageSender")
@SessionScoped
public class CourseManagedMsgSenderBean implements Serializable {

@Resource(name = "jms/CourseManagementCF")
private QueueConnectionFactory connectionFactory;
@Resource(lookup = "jms/courseManagementQueue")
private Queue queue;

QueueConnection connection;
QueueSession session;
Exception initException = null;

@PostConstruct
public void init() {
try {
connection = connectionFactory.createQueueConnection();
connection.start();
session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
} catch (Exception e) {
initException = e;
}
}

@PreDestroy
public void cleanup() {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
//TODO: log exception
}
}
}

public void addCourse(CourseDTO courseDTO) throws Exception {

if (initException != null)
throw initException;

QueueSender sender = session.createSender(queue);
ObjectMessage objMessage = session.createObjectMessage(courseDTO);
sender.send(objMessage);
}
}

Notice that the JMS connection factory and queue objects are injected using the @Resource annotation. We have used the @PostConstruct annotation to create a JMS a connection and a session and the @PreDestroy annotation for the clean-up operation. The addCourse method is similar to the code that we already implemented in the CourseQueueSender class in the previous section.

Let's now create the CourseJSFBean class in the packt.jee.eclipse.jms.jsf_bean package with the following content:

package packt.jee.eclipse.jms.jsf_bean;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

import packt.jee.eclipse.jms.dto.CourseDTO;;

@Named("course")
@RequestScoped
public class CourseJSFBean {
private CourseDTO courseDTO = new CourseDTO();

@Inject
private CourseManagedMsgSenderBean courseMessageSender;

public String getName() {
return this.courseDTO.getName();
}
public void setName(String name) {
this.courseDTO.setName(name);
}
public int getCredits() {
return this.courseDTO.getCredits();
}
public void setCredits(int credits) {
this.courseDTO.setCredits(credits);;
}

public void addCourse() throws Exception {
//skipping validation
//TODO: handle exception properly and show error message
courseMessageSender.addCourse(courseDTO);
}
}

An instance of CourseManagedMsgSenderBean is injected into CourseJSFBean using the @Inject annotation. The addCourse method simply calls the same named method in CourseManagedMsgSenderBean.

Finally, let's create addCourse.xhtml in the WebContents folder with the following content:

<html xmlns="http://www.w3.org/1999/xhtml" 
 xmlns:f="http://java.sun.com/jsf/core" 
 xmlns:h="http://java.sun.com/jsf/html"> 
 
<head> 
  <title>Add Course</title> 
</head> 
 
 <body> 
  <h2>Course Details</h2> 
 
  <h:form> 
    <table> 
      <tr> 
        <td>Name:</td> 
        <td> 
          <h:inputText id="course_name" value="#{course.name}"/> 
        </td> 
      </tr> 
      <tr> 
        <td>Credits:</td> 
        <td> 
          <h:inputText id="course_credits" 
value="#{course.credits}"/> </td> </tr> <tr> <td colspan="2"> <h:commandButton value="Submit"
action="#{course.addCourse}"/> </td> </tr> </table> </h:form> </body> </html>

Form fields are bound to fields in CourseJSFBean. When the Submit button is clicked, the addCourse method of the same bean is called, which puts a message in the JMS queue.

Republish the project and execute addCourse.xhtml by right-clicking it and selecting Run As | Run on Server. Add a course and see the message printed in the GlassFish Console view of Eclipse.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.227.82