Stand-alone client application to access EJB

In my previous blog (i.e. Getting started with Enterprise Java Beans (EJB)) I explained some basic concepts of Enterprise Java Beans (EJB) along with a sample application. So now when we are quite clear with EJB basic, lets drill bit deeper. Lets create a standalone client application to access enterprise java beans (EJB). The below application is in continuity with the application created in the previous blog.

1. Export the “MatheModuleEJB” jar file.
Right click on MatheModuleEJB –> Export –> EJB JAR File. Browse the destination to create the JAR file and click Finish.
12

2. Create a Java Project and name it as “MatheModuleClient“.
Go to New –> Project… —> Java Project.
12
Click Finish.

3. Create a simple java class inside MatheModuleClient.
Right click on MatheModuleClient –> New –> Class. Choose a package name eg. com.mf.ejbclient and a class name eg. RemoteEJBTest.
12
Click Finish.

Add the below code to the class.

package com.mf.ejbclient;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;

import com.mf.stateless.MathRemote;

public class RemoteEJBTest {

	public static void main(String[] args) {
		try {
			Hashtable env = new Hashtable();
			env.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
			env.put("java.naming.provider.url", "jnp://localhost:1099");
			env.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
			
			Context ctx = new InitialContext(env);
			
			MathRemote mathOperations = (MathRemote) ctx.lookup("MatheModule/MathRemoteBean/remote");
			
			System.out.println(mathOperations.add(95, 45));
			System.out.println(mathOperations.substract(95, 45));
		} catch (Exception e) {
			System.out.println(e.toString());
		}		
	}
}

4. Add MatheModuleEJB.jar to the application build path.
Right click on MatheModuleClient –> Build Path –> Configure Build Path… –> Libraries –> Add External JARs… –> Browse & Select MatheModuleEJB.jar.
12
Click Ok.

5. Add jbossall-client.jar to the application build path.
Right click on MatheModuleClient –> Build Path –> Configure Build Path… –> Libraries –> Add External JARs… –> Browse to the JBOSS_HOME/client/ & Select jbossall-client.jar.
12
Click Ok. This should add all JBoss client libraries to the Project Reference.

6. The application is ready to run. Right click on RemoteEJBTest –> Run As –> Java Application.

Console Output:
140.0
50.0

Hence we are able to call two methods add() and subtract() present on the JBoss server from a stand-alone client application.

Thanks for your time. Hope this helps.

Happy Coding… 🙂
Rupal Chatterjee
Software Engineer, Mindfire Solutions
http://www.mindfiresolutions.com
images
Connect me on Google, Facebook