Interceptor in Enterprise Java Bean

Below example demostractes how to create interceptor in Enterprise Java Bean

Below steps are to create Stateless session bean :

  • Create Enterprise Application Project StatelessInterceptor.ear.
  • Create interceptors in EJB project
  • Create Stateless Session Bean with Local interface in EJB project.
  • Add EJB project to Web Project
  • Create index.jsp in Web project.
  • Create Servlet in Web project.
  • Verify the project directory structure
  • Run the Application.
Step 1: Create Enterprise Application Project StatelessInterceptor.ear with EJB (StatelessInterceptorEJB)and Web (StatelessInterceptorWeb) Module

Click here if you are not familiear how to create Enterprise Application Project

Interceptor in EJB3
Specify the Enterprise Application Project name StatelessInterceptor and click Next

Below screen is used to create EJB and Web module in Enterprise Application Project. Click New Module
Interceptor in EJB3

Step 2: Create Interceptors in EJB project -
Interceptor1.java
package techmyguru.interceptors;
// all import statements
public class Interceptor1
{
@AroundInvoke
public Object logCall(InvocationContext ctxthrows Exception 
{
System.out.println("========= Interceptor 1: =========");
System.out.println("Method details " + ctx.getMethod());
Method method = ctx.getMethod();
String methodName = method.getName();
System.out.println("Method Name = " + methodName);

// get method parameters
System.out.println("Parameters if any - ");
Object obj[] = ctx.getParameters();
for (Object object : obj) {
  System.out.println(object.toString());
}

/*
Other way to get method parameters
System.out.println("-----------------"); 
get method parameters
if(methodName.equals("addtion")) {
System.out.println("parameter one - "+ctx.getParameters()[0]);
System.out.println("parameter two - "+ctx.getParameters()[1]); 
}
*/

System.out.println("before proceed method in Interceptor1 ");
Object obj1 = ctx.proceed();
System.out.println("after proceed method in Interceptor1 ");
return obj1;
}
}

Interceptor2.java
package techmyguru.interceptors;
// all import statements
public class Interceptor2 
{
@AroundInvoke
public Object logCall(InvocationContext contextthrows Exception 
{
  System.out.println("======== Interceptor 2: =========");
  System.out.println("Method details " + context.getMethod());
  Method method = context.getMethod();
  String methodName = method.getName();
  System.out.println("Method Name = " + methodName);
  System.out.println("before proceed method in Interceptor2 ");
  Object obj1 = context.proceed();
  System.out.println("after proceed method in Interceptor2 ");
  return obj1;
}
}

Interceptor3.java
package techmyguru.interceptors;
// all import statements
public class Interceptor3 
{
@AroundInvoke
public Object logCall(InvocationContext ctxthrows Exception 
{
System.out.println("=========== Interceptor 3: ==========");
System.out.println("Method details " + ctx.getMethod());
Method method = ctx.getMethod();

String methodName = method.getName();
System.out.println("Method Name = " + methodName);

// get method parameters
Object obj[] = ctx.getParameters();
for (Object object : obj) {
  System.out.println(object.toString());
}
System.out.println("-----------------");

// get method parameters
if (methodName.equals("multiplication")) {
  System.out.println("parameter one - " + ctx.getParameters()[0]);
  System.out.println("parameter two - " + ctx.getParameters()[1]);
}

// pass parameter to the target business logic
// It does not matter what parameter comes from user
// String para[] = { "10", "20" };
// ctx.setParameters(para);
System.out.println("before proceed method in Interceptor3 ");
return ctx.proceed();
}
}

Step 3: Create Stateless Session Bean class StatelessInterceptor and local interface StatelessInterceptorLocal :
Interceptor in EJB3
This step will create two java file. One will be local interface StatelessInterceptorLocal.java and other will be bean class StatelessInterceptor.java.

Edit both class java file as below :
StatelessInterceptorLocal.java
package techmyguru.interceptors;
import javax.ejb.Local;
@Local
public interface StatelessInterceptorLocal 
{
  public String addition(String num1, String num2);
  public String multiplication(String num1, String num2);
}

StatelessInterceptor.java
package techmyguru.interceptors;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;

// class level interceptor mapping 
@Stateless(mappedName = "statelessjndi3")
@Interceptors( { Interceptor1.class, Interceptor2.class })
public class StatelessInterceptor implements StatelessInterceptorLocal 
{
@Override
public String addition(String num1, String num2
{
String status = "";
try {
  int sum = Integer.parseInt(num1+ Integer.parseInt(num2);
  status = "The sum is =" + sum;
  catch (NumberFormatException e) {
  status = "Not valid Number" + e.getClass();
  }
  return status;
}

@Override
@Interceptors(Interceptor3.class)
public String multiplication(String num1, String num2) {
  String status = "";
  try {
  int multi = Integer.parseInt(num1* Integer.parseInt(num2);
  status = "The multiplication is " + multi;
  catch (NumberFormatException e) {
  status = "Not valid Number" + e.getClass();
  }
  return status;
}
}

Step 4: Add EJB project to Web Project
Right Click on Web Project (StatelessInterceptorWeb) - > Properties - > Java Build Path -> Click Projects -> Add -> Select StatelessInterceptorEJB.

Step 5: Create index.jsp in Web project -
index.jsp
<html>
<head>
<title>Interceptor Demo in EJB 3</title>
</head>
<body>
<h2>
<form action="Servlet1" method="post">
Enter first number <input type="text" name="num1"><br>
Enter second number <input type="text" name="num2"><br>
<input type="submit" value="Addition" name="task">
<input type="submit" value="Multiplication" name="task">
<input type="reset"
</form>
</h2>
</body>
</html>

Step 6: Create Servlet in Web project -
Servlet1.java
package techmyguru.web;
// all import statements
import techmyguru.interceptors.StatelessInterceptorLocal;
public class Servlet1 extends HttpServlet 
{
private static final long serialVersionUID = 1L;

@EJB
StatelessInterceptorLocal local;
protected void doPost(HttpServletRequest request,HttpServletResponse response)
    throws ServletException, IOException 
{
  PrintWriter pw = response.getWriter();
  String task = request.getParameter("task");
  String num1 = request.getParameter("num1");
  String num2 = request.getParameter("num2");
  pw.println("<h2>");
  if (task.trim().equals("Addition")) {
    pw.println(local.addition(num1, num2));
  else if (task.trim().equals("Multiplication")) {
    pw.println(local.multiplication(num1, num2));
  else
    pw.println("<br> Not valid request");
  pw.println("<br><a href='index.jsp'>Try Again</a>");
  pw.println("</h2>");
}
}

Step 8: Verify the directory structure as below -
Interceptor in EJB3

Step 7: Run the Application
Right click on Web Project -> Run As -> Run on Server
Interceptor in EJB3
Input two number and click Addition

You will get below output on server console -
Interceptor in EJB3

Open index.jsp once again and input two number and click Multiplication
Interceptor in EJB3

You will get below output on server console
Interceptor in EJB3


Previous Download Source Code Next


Write your Comment

Name :
Email Id : [ We will not publish your email id ]
Your Comment : [ Maximum 200 chars ]
Enter Security code