After you have created an EJB 3.x applications, you can create a Servlet or JSF to test
the EJB 3.x applications.
About this task
To test an EJB application with a servlet, you must first inject an EJB reference using the
@EJB injection annotation from EJB 3.x. Once you have injected the EJB, you can
call the methods that are available from the Remote or Local interface.
Procedure
- Testing EJB 3.x applications with a servlet
- Select and select Servlet.
- Type the package and class name for your servlet.
- After the servlet has been created and the Java™ editor
opened on the servlet class, insert the @EJB annotation tag along with the
reference to the local or remote interface class as a new field in the servlet.
- You can now invoke any of the methods in the local or remote interface from within the
doPost() or doGet() methods of your servlet.
The following snippet is taken from the EJB 3.x Counter sample. You will see the
statelessCounter field is declared with the type being
LocalCounter which is our local interface for the EJB. The @EJB
annotation in front of it injects an instance of it into our servlet.
// Use injection to get the ejb
@EJB private LocalCounter statelessCounter;
- Testing EJB 3.x applications with a JSF file
This type of testing currently requires some manual configuration steps. For an example of the
code involved, import the EJB 3.x Counter sample from the information center and locate the
EJBCounter.jsf file in the WebContent folder as well as the
page code Java classes in the Java sources in the EJBCounter.jsf project.