O'Reilly logo

Enterprise JavaBeans 3.0, 5th Edition by Bill Burke, Richard Monson-Haefel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 15. Interceptors

Interceptors are objects that are able to interpose themselves on method calls or the life cycle events of session and message-driven beans. They allow you to encapsulate common behavior that cuts across large parts of your application. This behavior is usually common code that you don't want to pollute your business logic. Where most of the changes to the EJB 3.0 specification were designed to make EJB easier to use for application developers, interceptors are an advanced feature that provide you another way to modularize your application or even extend your EJB container. This chapter teaches you how to write an interceptor as well as shows you various real-world examples of where interceptors can be used.

Intercepting Methods

To understand when to use interceptors, we'll look at some modified code of our TravelAgent EJB's bookPassage( ) method. The application developer of this code has added some profiling logic to time how long the bookPassage( ) method takes to be invoked. It is as simple as polling the current time at the start of the method and printing out the time it took at the end of it within a finally block:

@Remove
public TicketDO bookPassage(CreditCardDO card, double price)
    throws IncompleteConversationalState {long startTime = System.currentTimeMillis( );
   try { if (customer == null || cruise == null || cabin == null) { throw new IncompleteConversationalState( ); } try { Reservation reservation = new Reservation( customer, cruise, cabin, price, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required