默认情况下,任何 EJB 都绑定到 JNDI。您可以轻松地使用 JNDI 从您的 servlet 中定位会话 bean 并执行会话 bean。您真的不需要 MBean。
这是伪代码(只是伪代码,可能无法编译)
一个示例有状态 bean
package org.jboss.example;
import javax.ejb.Stateful;
@Stateful
public class StatefulBean {
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
访问上述 bean 的示例 servlet
package org.jboss.example;
import java.io.IOException;
import java.io.PrintWriter;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BeanServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter writer = response.getWriter();
StatefulBean statefulBean = getStatefulBean(request);
writer.println("State: " + statefulBean.getState());
}
private StatefulTestBean getStatefulBean(HttpServletRequest request)
throws ServletException {
StatefulBean sb = null;
try {
InitialContext ic = new InitialContext();
sb = (StatefulBean) ic.lookup("java:ejb/StatefulBean");
} catch (NamingException e) {
throw new ServletException(e);
}
}
return sb;
}
}