I got a question from a customer that he wants to use EJBContext from an EJB 3 Interceptor.
Yes, it’s very simple. Just inject the EJBContext into the interceptor using @Resource injection.
See the example code that uses methods of SessionContext as follows:
package actionbazaar.buslogic;
import javax.annotation.Resource;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
public class CheckPermissionInterceptor {
@Resource
private javax.ejb.SessionContext ctx;
@AroundInvoke
public Object checkUserRole(InvocationContext ic) throws Exception {
System.out.println("*** CheckPermission Interceptor invoked for "
+ ic.getTarget() + " ***");
if (!ctx.isCallerInRole("admin")) {
throw new SecurityException("User: '"
+ ctx.getCallerPrincipal().getName()
+ "' does not have permissions for method "
+ ic.getMethod());
}
return ic.proceed();
}
}
If you want the run-able version of the example code, you can download from http://manning.com/panda and look at Chapter 5 example.