简体   繁体   English

Java从servlet调用EJB

[英]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. 我有一个servlet,我想根据servlet获取的参数动态调用它的EJB对象。

What is the best way to invoke the EJB object and methods? 调用EJB对象和方法的最佳方法是什么?

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. 更新 :例如,我得到的参数是sessionBean的名称,所以我想调用它(通过它的名字),然后调用它内部的一些方法,因此它将动态创建。

Thank's In Advance. 提前致谢。

You can do this via a JNDI lookup. 您可以通过JNDI查找来完成此操作。

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. 这将检索MyEJB的远程接口,只需根据servlet参数创建查找字符串。 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. 在没有一系列@EJB注入的情况下获得此结果的最简单方法是使用查找。 Let's assume that you have figured out that you need an instance of EJB1, the lookup code will look like this: 假设您已经发现需要EJB1的实例,查找代码将如下所示:

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. 检查我们服务器的示例,了解在创建InitialContext和查找调用时使用的确切语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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