users@glassfish.java.net

Re: How do I access an EJB from JSP on GlassFish?

From: <glassfish_at_javadesktop.org>
Date: Tue, 09 Oct 2007 16:34:06 PDT

Assuming that the JSP WAR is bundled with the EJB in an EAR, then you should write a simple Service Location bean to perform the lookup for you:

[code]
package com.example.util;

public class ServiceLocator {
    public static YourSessionBeanLocal lookupYourSessionBean() {
        try {
            Context c = new InitialContext();
            return (YourSessionBeanLocal) c.lookup("java:comp/env/ejb/YourLocalSessionBean");
        } catch(NamingException ne) {
            // Do something proper here -- i.e. not this.
            ne.printStackTrace();
        }
    }
}
[/code]

Mind, if the WAR isn't in the EAR, then you just need to use a Remote call instead of a local call and change the JNDI name.

Then, you can simply use it inside a scriptlet within your JSP.

[code]
<jsp:useBean id="customer" class="com.example.beans.Customer"/>
<%
    YourSessionBeanLocal sessionBean = ServiceLocator.lookupYourSessionBean();
    customer = sessionBean.findCustomer(1);
%>
Customer name: ${customer.name}
[/code]

You can also just wrap that up in a tag file, making for a neater JSP:

[code]
WEB-INF/tags/customer.tag
<%_at_tag description="Locates a customer" pageEncoding="UTF-8"
     import="com.example.ejbs.YourSessionBeanLoca, com.example.beans.Customer, com.example.util.ServiceLocator"%>
<%_at_attribute name="id" required="true"%>
<%
    YourSessionBeanLocal sessionBean = ServiceLocator.lookupYourSessionBean();
    Customer customer = sessionBean.findCustomer(id);
    jspContext.setAttribute("customer", customer);
%>
[/code]

Then, in your JSP you simply do:

[code]
<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>

Here is the customer you requested: <br>
<t:customer id="${param.id}"/>
Customer Name: ${customer.name}<br>
Address: ${customer.address}<br>
[/code]

I find tag files a nice way to easily move scriptlet code out of my pages.
[Message sent by forum member 'whartung' (whartung)]

http://forums.java.net/jive/thread.jspa?messageID=239213