Java Reference
In-Depth Information
That's a neat way to intercept execution for a specific action bean. We
can also write an interceptor that runs for the whole application.
Implementing Interceptors
For a global interceptor, implement the
Interceptor
interface, and either
place the class in an extension package or configure it in the
web.xml
file.
The
Interceptor
interface is simple:
public interface
Interceptor {
Resolution intercept(ExecutionContext context)
throws
Exception;
}
To indicate the life-cycle stages that we want to intercept, we annotate
our class with
@Intercepts
. For example:
@Intercepts(LifecycleStage.ActionBeanResolution)
public class
MyInterceptor
implements
Interceptor {
public
Resolution intercept(ExecutionContext context) {
// ...
}
}
Instead of using
@Before
or
@After
to indicate whether our interceptor
code should run before or after the life-cycle stages, we call
proceed
( )
on the
ExecutionContext
object that's passed to the
intercept
( ) method.
That executes the life-cycle stage. So, the code we put around the call
to
proceed
( ) is executed before or after, accordingly:
@Intercepts(LifecycleStage.ActionBeanResolution)
public class
MyInterceptor
implements
Interceptor {
public
Resolution intercept(ExecutionContext context)
// proceed() can throw an Exception so we have to declare it
throws
Exception
{
// do something before
Resolution resolution = context.proceed();
// do something after
return
resolution;
}
}
Notice how
proceed
( ) returns a resolution; returning that value from
intercept
( ) effectively lets the life-cycle sequence continue normally. If,
Search WWH ::
Custom Search