Saturday, March 14, 2009

How can my JSP page communicate with an EJB Session Bean? (JSP)

Question :How can my JSP page communicate with an EJB Session Bean? (JSP)
Answer :The following is a code snippet that demonstrates how a JSP page can
interact with an EJB session bean:
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account" %>
<%!
//declare a "global" reference to an instance of the home interface of the
session bean
AccountHome accHome=null;
public void jspInit() {
//obtain an instance of the home interface
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome =
(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>
<%
//instantiate the session bean
Account acct = accHome.create();
//invoke the remote methods
acct.doWhatever(...);
// etc etc...
%>

No comments: