How to Invoke an Enterprise Java Bean (EJB) from a JSP page : WildFly and Eclipse

JSP ( Java Server Pages )technology is used to create web application just like Servlet technology. It can be thought of as an extension to the servlet because it provides more functionality than servlet. A JSP page contains HTML code and JSP tags.

The structure of the project done through this tutorial is shown below:

1 Open your Eclipse J2EE version, Make sure that the J2EE Button is selected as shown below

2 Select File – > New -> Dynamic Web Project

3 Type the name project name as : HelloJSP-EJB and click Finish. Make sure hat the target runtime is selected for WildFly

4 Right click on the HelloJSP-EJB project, select New -> JSP File

5 Type in the name for the file as : index.jsp as shown below. Click Finish once done.

6 Use the code below for the index.jsp file

<%@ page import="com.logic.*" language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello from JSP</title>

<% out.print("<h1>My Addition Application</h1>"); %>
Welcome to the addition Application<br>
Current Time is : <%=new java.util.Date()%>
javax.naming.InitialContext ic = new javax.naming.InitialContext();
AdditionRemote abc=(AdditionRemote)ic.lookup("ejb:/MyAdditionEJB//Addition!com.logic.AdditionRemote"); 
int a=abc.add(5,7);
out.println("Result is : "+a);
JSP are simple java code that is enclosed between <% and %>

7 Save the file index.jsp

There are a few errors that you need to fix by importing the EJB Jar file

8 In case you don’t have the EJB Jar file generated yet, Right click on the MyAdditionEJB project and select Export –> Export as shown :

9 Select EJB –> EJB Jar File as shown:

10 Click Browse to select a place to store the JAR file ( Ex, your Desktop or C: drive …). Click Finish once done.

11 Now, Open the lib folder under WebContent–>WEB-INF for the HelloJSP-EJB project. Copy and paste MyAdditionEJB.jar file.

12 To remove the errors, Right click on the project HelloJSP-EJB and click Refresh

13 Time to deploy the JSP project now, right click on the project, select Run As –>Run on Server

14 Make sure you select the WildFly Runtime server, Click Finish

15 That’s it. To test your application, you can open any Browser such as Chrome or Firefox or Explorer and visit the address: