简体   繁体   中英

Java invoke EJB from servlet

I have a servlet that I want to dynamically call an EJB object from it accordinally to the parameter the servlet gets.

What is the best way to invoke the EJB object and methods?

UPDATE : for example, the parameter I get is the sessionBean's name , so I want to invoke it (by it's name) and then call some methods inside of it, so it will be created dynamically.

Thank's In Advance.

You can do this via a JNDI lookup.

InitialContext ic = new InitialContext();
MyEJB ejb = (MyEJB) ic.lookup("java:comp/env/MyEJB");

This will retrieve the remote interface of MyEJB, just create the lookup string based on servlet parameters. If you have no clue on the methods, you should use reflection to find out.

The easiest way to get this result without a whole series of @EJB injections is to use lookup. Let's assume that you have figured out that you need an instance of EJB1, the lookup code will look like this:

private EJB1 ejb1 = null;
try {
    InitialContext ic = new InitialContext();
    ejb1 = (EJB1)
            ic.lookup(ejb1.class.getName());
    ejb1.method1();
} catch (Exception ex) {
    logger.log(Level.SEVERE,"Couldn’t create converter bean.",ex);
}

Check our server's examples for the exact syntax to be used in the creation of the InitialContext and the lookup call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM