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:
eclipse-j2ee-servlet-example17

1 Open your Eclipse J2EE version, Make sure that the J2EE Button is selected as shown below
eclipse-j2ee-servlet-example1

2 Select File – > New -> Dynamic Web Project
eclipse-j2ee-servlet-example2

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

4 Right click on the HelloJSP-EJB project, select New -> JSP File
eclipse-j2ee-servlet-example4

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

6 Use the code below for the index.jsp file

<%@ page import="com.logic.*" language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello from JSP</title>
</head>
<body>

<% out.print("<h1>My Addition Application</h1>"); %>
<hr> 
Welcome to the addition Application<br>
Current Time is : <%=new java.util.Date()%>
<hr>
<%
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);
%>
</body>
</html>
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 :
invoke-ejb-from-java-application

9 Select EJB –> EJB Jar File as shown:
invoke-ejb-from-java-application1

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


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

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

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

14 Make sure you select the WildFly Runtime server, Click Finish
ejb-jsp-wildfly4

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


ejb-jsp-wildfly8