The billpayment Example: Using Events and Interceptors (original) (raw)
2. Using the Tutorial Examples
3. Getting Started with Web Applications
4. JavaServer Faces Technology
7. Using JavaServer Faces Technology in Web Pages
8. Using Converters, Listeners, and Validators
9. Developing with JavaServer Faces Technology
10. JavaServer Faces Technology: Advanced Concepts
11. Using Ajax with JavaServer Faces Technology
12. Composite Components: Advanced Topics and Example
13. Creating Custom UI Components and Other Custom Objects
14. Configuring JavaServer Faces Applications
16. Uploading Files with Java Servlet Technology
17. Internationalizing and Localizing Web Applications
18. Introduction to Web Services
19. Building Web Services with JAX-WS
20. Building RESTful Web Services with JAX-RS
21. JAX-RS: Advanced Topics and Example
23. Getting Started with Enterprise Beans
24. Running the Enterprise Bean Examples
25. A Message-Driven Bean Example
26. Using the Embedded Enterprise Bean Container
27. Using Asynchronous Method Invocation in Session Beans
Part V Contexts and Dependency Injection for the Java EE Platform
28. Introduction to Contexts and Dependency Injection for the Java EE Platform
29. Running the Basic Contexts and Dependency Injection Examples
30. Contexts and Dependency Injection for the Java EE Platform: Advanced Topics
31. Running the Advanced Contexts and Dependency Injection Examples
The encoder Example: Using Alternatives
The Coder Interface and Implementations
The encoder Facelets Page and Managed Bean
To Build, Package, and Deploy the encoder Example Using NetBeans IDE
To Run the encoder Example Using NetBeans IDE
To Build, Package, and Deploy the encoder Example Using Ant
To Run the encoder Example Using Ant
The producermethods Example: Using a Producer Method To Choose a Bean Implementation
Components of the producermethods Example
Running the producermethods Example
To Build, Package, and Deploy the producermethods Example Using NetBeans IDE
To Build, Package, and Deploy the producermethods Example Using Ant
To Run the producermethods Example
The producerfields Example: Using Producer Fields to Generate Resources
The Producer Field for the producerfields Example
The producerfields Entity and Session Bean
The producerfields Facelets Pages and Managed Bean
Running the producerfields Example
To Build, Package, and Deploy the producerfields Example Using NetBeans IDE
To Build, Package, and Deploy the producerfields Example Using Ant
To Run the producerfields Example
The decorators Example: Decorating a Bean
Components of the decorators Example
Running the decorators Example
To Build, Package, and Deploy the decorators Example Using NetBeans IDE
To Build, Package, and Deploy the decorators Example Using Ant
32. Introduction to the Java Persistence API
33. Running the Persistence Examples
34. The Java Persistence Query Language
35. Using the Criteria API to Create Queries
36. Creating and Using String-Based Criteria Queries
37. Controlling Concurrent Access to Entity Data with Locking
38. Using a Second-Level Cache with Java Persistence API Applications
39. Introduction to Security in the Java EE Platform
40. Getting Started Securing Web Applications
41. Getting Started Securing Enterprise Applications
42. Java EE Security: Advanced Topics
Part VIII Java EE Supporting Technologies
43. Introduction to Java EE Supporting Technologies
45. Resources and Resource Adapters
46. The Resource Adapter Example
47. Java Message Service Concepts
48. Java Message Service Examples
49. Bean Validation: Advanced Topics
50. Using Java EE Interceptors
51. Duke's Bookstore Case Study Example
52. Duke's Tutoring Case Study Example
53. Duke's Forest Case Study Example
The billpayment example shows how to use both events and interceptors.
The example simulates paying an amount using a debit card or credit card. When the user chooses a payment method, the managed bean creates an appropriate event, supplies its payload, and fires it. A simple event listener handles the event using observer methods.
The example also defines an interceptor that is set on a class and on two methods of another class.
The PaymentEvent Event Class
The event class, event.PaymentEvent, is a simple bean class that contains a no-argument constructor. It also has a toString method and getter and setter methods for the payload components: a String for the payment type, a BigDecimal for the payment amount, and a Date for the timestamp.
public class PaymentEvent implements Serializable {
...
public String paymentType;
public BigDecimal value;
public Date datetime;
public PaymentEvent() {
}
@Override
public String toString() {
return this.paymentType
+ " = $" + this.value.toString()
+ " at " + this.datetime.toString();
}
...
The event class is a simple bean that is instantiated by the managed bean using new and then populated. For this reason, the CDI container cannot intercept the creation of the bean, and hence it cannot allow interception of its getter and setter methods.
The PaymentHandler Event Listener
The event listener, listener.PaymentHandler, contains two observer methods, one for each of the two event types:
@Logged @SessionScoped public class PaymentHandler implements Serializable {
...
public void creditPayment(@Observes @Credit PaymentEvent event) {
logger.log(Level.INFO, "PaymentHandler - Credit Handler: {0}",
event.toString());
// call a specific Credit handler class...
}
public void debitPayment(@Observes @Debit PaymentEvent event) {
logger.log(Level.INFO, "PaymentHandler - Debit Handler: {0}",
event.toString());
// call a specific Debit handler class...
}
}
Each observer method takes as an argument the event, annotated with @Observesand with the qualifier for the type of payment. In a real application, the observer methods would pass the event information on to another component that would perform business logic on the payment.
The qualifiers are defined in the payment package, described in The billpayment Facelets Pages and Managed Bean.
Like PaymentEvent, the PaymentHandler bean is annotated @Logged, so that all its methods can be intercepted.
The billpayment Facelets Pages and Managed Bean
The billpayment example contains two Facelets pages, index.xhtml and the very simpleresponse.xhtml. The body of index.xhtml looks like this:
<h:body>
<h3>Bill Payment Options</h3>
<p>Type an amount, select Debit Card or Credit Card,
then click Pay.</p>
<h:form>
<p>
<h:outputLabel value="Amount: $" for="amt"/>
<h:inputText id="amt" value="#{paymentBean.value}"
required="true"
requiredMessage="An amount is required."
maxlength="15" />
</p>
<h:outputLabel value="Options:" for="opt"/>
<h:selectOneRadio id="opt" value="#{paymentBean.paymentOption}">
<f:selectItem id="debit" itemLabel="Debit Card"
itemValue="1"/>
<f:selectItem id="credit" itemLabel="Credit Card"
itemValue="2" />
</h:selectOneRadio>
<p><h:commandButton id="submit" value="Pay"
action="#{paymentBean.pay}" /></p>
<p><h:commandButton value="Reset"
action="#{paymentBean.reset}" /></p>
</h:form>
...
</h:body>
The input text field takes a payment amount, passed to paymentBean.value. Two radio buttons ask the user to select a Debit Card or Credit Card payment, passing the integer value to paymentBean.paymentOption. Finally, the Pay command button’s action is set to the method paymentBean.pay, while the Reset button’s action is set to the paymentBean.reset method.
The payment.PaymentBean managed bean uses qualifiers to differentiate between the two kinds of payment event:
@Named @SessionScoped public class PaymentBean implements Serializable {
... @Inject @Credit Event creditEvent;
@Inject
@Debit
Event<PaymentEvent> debitEvent;
The qualifiers, @Credit and @Debit, are defined in the payment package along withPaymentBean.
Next, the PaymentBean defines the properties it obtains from the Facelets page and will pass on to the event:
public static final int DEBIT = 1;
public static final int CREDIT = 2;
private int paymentOption = DEBIT;
@Digits(integer = 10, fraction = 2, message = "Invalid value")
private BigDecimal value;
private Date datetime;
The paymentOption value is an integer passed in from the radio button component; the default value is DEBIT. The value is a BigDecimal with a Bean Validation constraint that enforces a currency value with a maximum number of digits. The timestamp for the event, datetime, is a Date object initialized when thepay method is called.
The pay method of the bean first sets the timestamp for this payment event. It then creates and populates the event payload, using the constructor for the PaymentEvent and calling the event’s setter methods using the bean properties as arguments. It then fires the event.
@Logged
public String pay() {
this.setDatetime(Calendar.getInstance().getTime());
switch (paymentOption) {
case DEBIT:
PaymentEvent debitPayload = new PaymentEvent();
debitPayload.setPaymentType("Debit");
debitPayload.setValue(value);
debitPayload.setDatetime(datetime);
debitEvent.fire(debitPayload);
break;
case CREDIT:
PaymentEvent creditPayload = new PaymentEvent();
creditPayload.setPaymentType("Credit");
creditPayload.setValue(value);
creditPayload.setDatetime(datetime);
creditEvent.fire(creditPayload);
break;
default:
logger.severe("Invalid payment option!");
}
return "/response.xhtml";
}
The pay method returns the page to which the action is redirected, response.xhtml.
The PaymentBean class also contains a reset method that empties the value field on the index.xhtml page and sets the payment option to the default:
@Logged
public void reset() {
setPaymentOption(DEBIT);
setValue(BigDecimal.ZERO);
}
In this bean, only the pay and reset methods are intercepted.
The response.xhtml page displays the amount paid. It uses a rendered expression to display the payment method:
<h:body>
<h:form>
<h2>Bill Payment: Result</h2>
<h3>Amount Paid with
<h:outputText id="debit" value="Debit Card: "
rendered="#{paymentBean.paymentOption eq 1}" />
<h:outputText id="credit" value="Credit Card: "
rendered="#{paymentBean.paymentOption eq 2}" />
<h:outputText id="result" value="#{paymentBean.value}" >
<f:convertNumber type="currency"/>
</h:outputText>
</h3>
<p><h:commandButton id="back" value="Back" action="index" /></p>
</h:form>
</h:body>
The LoggedInterceptor Interceptor Class
The interceptor class, LoggedInterceptor, and its interceptor binding, Logged, are both defined in the interceptor package. The Logged interceptor binding is defined as follows:
@Inherited −@InterceptorBinding @Retention(RUNTIME) @Target({METHOD, TYPE}) public @interface Logged { }
The LoggedInterceptor class looks like this:
@Logged @Interceptor public class LoggedInterceptor implements Serializable {
...
public LoggedInterceptor() {
}
@AroundInvoke
public Object logMethodEntry(InvocationContext invocationContext)
throws Exception {
System.out.println("Entering method: "
+ invocationContext.getMethod().getName() + " in class "
+ invocationContext.getMethod().getDeclaringClass().getName());
return invocationContext.proceed();
}
}
The class is annotated with both the @Logged and the @Interceptor annotations. The@AroundInvoke method, logMethodEntry, takes the required InvocationContext argument, and calls the required proceedmethod. When a method is intercepted, logMethodEntry displays the name of the method being invoked as well as its class.
To enable the interceptor, the beans.xml file defines it as follows:
billpayment.interceptor.LoggedInterceptorIn this application, the PaymentEvent and PaymentHandler classes are annotated @Logged, so all their methods are intercepted. In PaymentBean, only the pay and reset methods are annotated@Logged, so only those methods are intercepted.
Running the billpayment Example
You can use either NetBeans IDE or Ant to build, package, deploy, and run the billpayment application.
To Build, Package, and Deploy the billpayment Example Using NetBeans IDE
- From the File menu, choose Open Project.
- In the Open Project dialog, navigate to:
tut-install/examples/cdi/ - Select the billpayment folder.
- Select the Open as Main Project check box.
- Click Open Project.
- In the Projects tab, right-click the billpayment project and select Deploy.
To Build, Package, and Deploy the billpayment Example Using Ant
- In a terminal window, go to:
tut-install/examples/cdi/billpayment/ - Type the following command:
ant
This command calls the default target, which builds and packages the application into a WAR file, billpayment.war, located in the dist directory. - Type the following command:
ant deploy
To Run the billpayment Example
- In a web browser, type the following URL:
http://localhost:8080/billpayment
The Bill Payment Options page opens. - Type a value in the Amount field.
The amount can contain up to 10 digits and include up to 2 decimal places. For example:
9876.54 - Select Debit Card or Credit Card and click Pay.
The Bill Payment: Result page opens, displaying the amount paid and the method of payment:
Amount Paid with Credit Card: $9,876.34 - (Optional) Click Back to return to the Bill Payment Options page.
You can also click Reset to return to the initial page values. - Examine the server log output.
In NetBeans IDE, the output is visible in the GlassFish Server 3+ output window. Otherwise, view domain-dir/logs/server.log.
The output from each interceptor appears in the log, followed by the additional logger output defined by the constructor and methods.
Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Legal Notices