Skip Headers
Oracle® Application Server Containers for J2EE JSP Tag Libraries and Utilities Reference
10g Release 2 (10.1.2)
B14016-02
  Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Previous
Previous
Next
Next
 

9 JSP Utilities and Utility Tags

This chapter, consisting of the following sections, documents various OC4J utility features for JSP pages:

JSP Event-Handling with JspScopeListener


Important:

JspScopeListener is deprecated in the OC4J 10.1.2 implementation and will be desupported in later implementations. Most of its functionality is available in standard features of J2EE 1.4 or higher.

In standard servlet and JSP technology, only session-based events are supported. Oracle extends this support to page-based, request-based, and application-based events through the JspScopeListener interface and JspScopeEvent class in the oracle.jsp.event package.

JspScopeListener functionality is documented in the following sections, concluding with examples:

General Use of JspScopeListener

For Java objects in your application, implement the JspScopeListener interface in the appropriate class, then attach objects of that class to a JSP scope using tags such as jsp:useBean.

When the end of a scope is reached, objects that implement JspScopeListener and have been attached to the scope will be notified. The JSP container accomplishes this by sending a JspScopeEvent instance to such objects through the outOfScope() method specified in the JspScopeListener interface.

This event listener mechanism significantly benefits developers who want to always free object resources that are of page or request scope, regardless of error conditions. It frees these developers from having to surround their page implementations with Java try/catch/finally blocks.

Properties of the JspScopeEvent object include the following:

  • Scope that is ending, represented by one of the int constants PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, or APPLICATION_SCOPE

    You can retrieve this scope with the following JspScopeEvent method:

    public int getScope()
    
    
  • Container object that is the repository for objects at this scope, one of the implicit objects page, request, session, or application

    This is the object that manages the relevant scope. You can retrieve this object with the following JspScopeEvent method:

    public java.lang.Object getContainer()
    
    
  • Name of the object to which the notification pertains

    This is the name of the instance of the class that implements JspScopeListener. The instance of this class is an attribute of either the page, request, session, or application object (as applicable), so this instance name is the attribute name. You can retrieve this name with the following JspScopeEvent method:

    public String getName()
    
    
  • JSP implicit application object

    You can retrieve this with the following JspScopeEvent method:

    public ServletContext getApplication()
    
    

The JspScopeEvent class has a constructor as follows:

public JspScopeEvent (ServletContext sc, Object container, String name,
                      int scope)

Use of JspScopeListener in OC4J and Other Servlet 2.3 Environments

JspScopeListener uses different mechanisms to support the different scopes, though all are implemented according to servlet and JSP standards.

For pages running in an OC4J environment, there is also an OC4J-specific runtime implementation for page scope, for convenience.

These features are covered in the following sections:

Requirements for JspScopeListener

The JspScopeListener implementation requires the following:

  • The oracle.jsp.event.JspScopeListener interface and JspScopeEvent class, and the classes of the oracle.jsp.event.impl package, all of which are supplied in the ojsp.jar file

  • A servlet 2.3 or higher environment (such as OC4J)

Runtime and Tag Implementations to Support Page Scope

For OC4J environments, there is support for page scope functionality through an Oracle-specific runtime implementation. Enable this by setting the JSP check_page_scope configuration parameter to true. The default is false, for performance reasons.

For portability to other environments, there is also an implementation to support page scope through a custom tag, checkPageScope. Put the appropriate code between the checkPageScope start-tag and end-tag. This tag, with no attributes, is defined as follows:

<!-- The checkPageScope tag -->
<tag>
   <name>checkPageScope</name>
   <tagclass>oracle.jsp.jml.tagext.CheckPageScopeListenerTag</tagclass>
   <bodycontent>JSP</bodycontent>
   <info>
      To provide the notification logic for any
      JspScopeListener stored in page scope.
      This tag is not needed on OC4J.
   </info>
</tag>

Here is an example of its use:

<%@ taglib uri="http://xmlns.oracle.com/j2ee/jsp/tld/ojsp/jml.tld" 
           prefix="jml" %>
<jml:checkPageScope>
pagescope.jsp
<jsp:useBean id="tb" class="testpkg.TestData" />
<% 
   /* testpkg.TestData implements oracle.jsp.event.JspScopeListener.  
      checkPageScope tag will provide the notification logic for any
      JspScopeListener stored in page scope.
      This tag is not needed on OC4J.
   */
   // some more JSP / code here ...
%>
<%= new java.util.Date() %>
</jml:checkPageScope>

Note:

The checkPageScope tag is currently part of the Oracle JML tag library, which is included in the ojsputil.jar file and requires the jml.tld tag library descriptor file. An appropriate taglib directive is shown in the preceding example. See "Overview of the JSP Markup Language (JML) Tag Library" for related information.

Servlet Filter Implementation to Support Request Scope

Objects of request scope are supported through a servlet filter. The filtering applies to any servlets matching a specified URL pattern.

For support of event-handling for request-scope objects, add an entry such as the following to the web.xml file for your application, or to orion-web.xml or global-web-application.xml as appropriate. To ensure proper operation of the JspScopeListener functionality, this setting must be after any other filter settings.

<filter> 
   <filter-name>Request Filter</filter-name> 
   <filter-class>oracle.jsp.event.impl.RequestScopeFilter</filter-class> 
</filter> 
<!-- Define filter mappings for the defined filters --> 
<filter-mapping> 
   <filter-name>Request Filter</filter-name> 
   <url-pattern>/jsp/*</url-pattern> 
</filter-mapping> 


Note:

In this particular example, "/jsp/*" is the URL pattern covered by the filter. Users can choose other patterns instead, such as "/*.jsp" or "/*".

Listener Class Implementation to Support Application Scope

Objects with application scope are supported through a servlet context listener implementation class, in accordance with the servlet specification.

For support of event-handling for application-scope objects, add an entry such as the following to the web.xml file for your application. To ensure proper operation of the JspScopeListener functionality, this setting must be after any other listener settings.

<listener> 
   <listener-class>oracle.jsp.event.impl.AppScopeListener</listener-class> 
</listener> 

For an application-scope object, in addition to notification upon the conclusion of the application and servlet context, there is notification when an attribute is replaced in the servlet context or removed from the servlet context. For example, the listener outOfScope() method of an application-scope object is called in either of the following circumstances, assuming a servlet context object ctx:

ctx.setAttribute("name", "Smith");
...
ctx.setAttribute("name, "Jones");

or:

ctx.setAttribute("name", "Smith");
...
ctx.removeAttribute("name");


Note:

This functionality was not available prior to Oracle9iAS Release 2.

Integration with HttpSessionBindingListener to Support Session Scope

For session-scope objects, you can write a class that implements both the JspScopeListener interface and the standard javax.servlet.http.HttpSessionBindingListener interface. This would give you the flexibility of supporting instances of this class for other scopes as well. If instances would never be used outside of session scope, however, there is no need to implement JspScopeListener.

In the integration scenario, the valueUnbound() method, specified in the HttpSessionBindingListener interface, should call the outOfScope() method that is specified in the JspScopeListener interface.

Following is a basic example:

import oracle.jsp.event.impl.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 

class SampleObj implements HttpSessionBindingListener,JspScopeListener 
{ 
   public void valueBound(HttpSessionBindingEvent e) 
   { 
      System.out.println("The object implements the JspScopeListener also"); 
   } 

   public void valueUnBound(HttpSessionBindingEvent e) 
   { 
      try 
      { 
         outOfScope(new JspScopeEvent(null,(Object)e.getSession(),
             e.getName(),javax.servlet.jsp.PageContext.SESSION_SCOPE)); 
      } catch (Throwable e) {} 
   ........... 
   } 
   public void outOfScope(JspScopeEvent e)
   {...}
}

Examples Using JspScopeListener

This section provides two examples of JspScopeListener usage: a JSP page and accompanying JavaBean, then a servlet.

Example: JSP Page Using JspScopeListener

This example consists of a JavaBean, ScopeDispatcher, that implements the JspScopeListener interface, and a JSP page that uses ScopeDispatcher instances for request-scope and application-scope functionality.

bookcatalog.jsp

The bookcatalog.jsp page allows users to search for a book in the catalog or insert a new book entry. The catalog is kept in a hashtable that is initially read from the local file stream.

At the end of a request, if a new book has been submitted: 1) the book is entered into the application-level catalog hashtable; 2) the book count increments.

At the end of execution of the application, the catalog hashtable is sent back to the local file stream, the number of newly inserted books is shown, and query results are displayed if there was a book search.

<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%! static int newbookCount = 0; %>
<%! static Hashtable catalog; %>
<%! boolean bookAdded = false; %>
<html>
<head>
<title> BookStore Price catalog </title>
</head>
<body bgcolor="white">
<font size=5 color="red">
<table color="#FFFFCC" width="100%" border="1" cellspacing="0" cellpadding="0" >
<tr>
<td>
<form action="bookcatalog.jsp">
<b> BookName </b>
<input type="text" name="bookname">
<input type="submit" value="Get the Price">
</form>
</td>
<td>
<form action="bookcatalog.jsp">
<b>BookName</b>
<input type="text" name="new_book">
<br>
<b>Price</b>
<input type="text" name="price">
<input type="submit" value="Add to Catalog">
</form>
</td>
</tr>
</table>

<%
  String bookname = request.getParameter("bookname");
  catalog = (Hashtable) application.getAttribute("pricelist");
  if (catalog == null)
  {
   try{
    ObjectInputStream oin = new ObjectInputStream
                           (new FileInputStream("bookcatalog.out"));
    Object obj =  oin.readObject();
    catalog = (Hashtable) obj;
    oin.close();
   }
  catch(Exception e) {
   catalog = new Hashtable();}
  application.setAttribute("pricelist",catalog);
 }
  if (bookname != null)
  {
    String price = (String) catalog.get(bookname.trim());
    if (price != null)
    {
     out.println("<h2>Book : " +bookname+ "</h2>");
     out.println("<h2>Price: "+price +"</h2>");
    }
    else
      out.println("<h2> Sorry, the  Book : " + bookname + " is not available in
                     the catalog</h2>");
  }
%>

<%-- declare the event dispatchers --%>
<jsp:useBean id = "requestDispatcher" 
             class = "oracle.jsp.sample.event.ScopeDispatcher" 
             scope = "request" >
   <jsp:setProperty name = "requestDispatcher" property = "page" 
                    value = "<%= this %>" />
   <jsp:setProperty name = "requestDispatcher" property = "methodName" 
                    value = "request_OnEnd" />
</jsp:useBean>

<jsp:useBean id = "appDispatcher" 
             class = "oracle.jsp.sample.event.ScopeDispatcher" 
             scope = "application" >
   <jsp:setProperty name = "appDispatcher" property = "page" 
                    value = "<%= this %>" />
   <jsp:setProperty name = "appDispatcher" property = "methodName" 
                    value = "application_OnEnd" />
</jsp:useBean>
<%! 
   // request_OnEnd Event Handler
   public void request_OnEnd(HttpServletRequest request) {
      // acquire beans
               String newbook  = request.getParameter("new_book");
               bookAdded = false;
               if ((newbook != null) && (!newbook.equals("")))
               {
                  catalog.put(newbook,request.getParameter("price"));
                  newbookCount++;
                  bookAdded = true;
               }
   }
%>

<%!
  public void application_OnEnd(ServletContext application)
  {
    try
    {
      ObjectOutputStream os = new ObjectOutputStream(
                                  new FileOutputStream("bookcatalog.out"));
      os.writeObject(catalog);
      os.flush();
      os.close();
    }
    catch (Exception e)
    {}
  }
%>

<%
if (bookAdded)
   out.println("<h2> The New book is been added in the catalog </h2>");
%>
<%-- Page implementation goes here --%>
<h2> Total number of books added is <%= newbookCount %></h2>
</font>
</body>
</html>
ScopeDispatcher.java

package oracle.jsp.sample.event;
import java.lang.reflect.*;
import oracle.jsp.event.*;

public class ScopeDispatcher extends Object implements JspScopeListener {
    private Object page;
    private String methodName;
    private Method method;

    public ScopeDispatcher() {
    }

    public Object getPage() {
        return page;
    }

    public void setPage(Object page) {
        this.page = page;
    }

    public String getMethodName() {
        return methodName;
    }

    public void setMethodName(String m) throws NoSuchMethodException,
                                               ClassNotFoundException  {
        method = verifyMethod(m);
        methodName = m;
    }

    public void outOfScope(JspScopeEvent ae) {
        int scope = ae.getScope();

        if ((scope == javax.servlet.jsp.PageContext.REQUEST_SCOPE  || 
             scope == javax.servlet.jsp.PageContext.APPLICATION_SCOPE)
             && method != null) {
            try {
                Object args[] = {ae.getContainer()};
                method.invoke(page, args);
            } catch (Exception e) {
                // catch all and continue
            }
        }
    }

    private Method verifyMethod(String m) throws NoSuchMethodException,
                                                 ClassNotFoundException {
        if (page == null) throw new NoSuchMethodException(
                                   "A page hasn't been set yet.");

        // Don't know whether this is a request or page handler so try one then
       // the other
        Class c = page.getClass();
        Class pTypes[] = {Class.forName("javax.servlet.ServletContext")};

        try {
            return c.getDeclaredMethod(m, pTypes);
        } catch (NoSuchMethodException nsme) {
            // fall through and try the request signature
        }

        pTypes[0] = Class.forName("javax.servlet.http.HttpServletRequest");
        return c.getDeclaredMethod(m, pTypes);
    }
}

Example: Servlet Using JspScopeListener

This section contains a sample servlet that uses JspScopeListener functionality for a request-scope object. The nested class DBScopeObj implements the JspScopeListener interface.

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
import oracle.jsp.event.*;
import oracle.jsp.event.impl.*;

public class RequestScopeServlet extends HttpServlet {
 
    PrintWriter out;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        out         = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<head>");
        out.println("<title> RequestScopeServlet! </title>");
        out.println("</head>");
        response.setContentType("text/html");
        DBScopeObj aobj = new DBScopeObj();
        request.setAttribute("dbcon",aobj);
        request.setAttribute("name","scott");
        request.setAttribute("company","oracle");
        request.setAttribute("city","sanmateo");
        Enumeration en = request.getAttributeNames();
        out.println("<BR> Request Attributes : <BR> <BR>");
        while (en.hasMoreElements()) {
            String key = (String)en.nextElement();
            Object value = request.getAttribute(key);
            out.println(key + "   : " + value+"<BR>");
         }
        out.println("</body>");
        out.println("</html>");
    }

    class DBScopeObj implements JspScopeListener
    {
       public void initDBConnection()
       {
            //  can create a minimum number of predefined
            // DBConnections
       }

       DBScopeObj()
       {
           // if DBconnection is available in the connection 
           // pool then pickup from the pool and give the handle. 
       }

       public void outOfScope(JspScopeEvent e)
       {
        ServletContext ctx = e.getApplication();
        out.println
            ("<BR>*****************************************************");
        out.println("<BR> JspScopeEvent <BR>");
        out.println("<BLINK>");
        out.println
            ("<BR> In outOfScope method for the Request Attribute <BR>");
        out.println("Name =  " +e.getName() + "<BR>");
        out.println("</BLINK>");
        out.println
            ("*****************************************************<BR>");
        // logging in the context also 

        ctx.log("*****************************************************");
        ctx.log(" JspScopeEvent ");
        ctx.log(" In outOfScope method for the Request Attribute ");
        ctx.log("Name =  " +e.getName());
        ctx.log("*****************************************************");
        returnDBConnection();
       }

       public void returnDBConnection()

       {
           //Can return the handle to the connection pool
       }
    }
}

EJB Tags

OC4J provides a custom tag library to simplify the use of Enterprise JavaBeans in JSP pages. The library includes tags to create a home instance, create an EJB instance, and iterate through a collection of EJBs.

The functionality of the OC4J EJB tags follows the J2EE specification. The tags allow you to instantiate EJBs by name, using configuration information in the web.xml file. One of the tags is a useBean tag, with functionality similar to that of the jsp:useBean tag for invoking a regular JavaBean.

The following sections document the tags, concluding with examples:

EJB Tag Configuration

Use an <ejb-ref> element in your application web.xml file for each EJB you will use, as in the following example:

<ejb-ref>
   <ejb-ref-name>ejb/DemoSession</ejb-ref-name>
   <ejb-ref-type>Session</ejb-ref-type>
   <home>ejbdemo.DemoSessionHome</home>
   <remote>ejbdemo.DemoSession</remote> 
</ejb-ref>

The <ejb-ref> element and its subelements, or <ejb-local-ref> to use local interfaces, are used according to the servlet specification. Briefly, this is as follows:

  • The <ejb-ref-name> subelement specifies a reference name that can be used by other components of a J2EE application to access this component. For example, this name could be used in a location value.

  • The <ejb-ref-type> subelement specifies the category of EJB.

  • The <home> subelement specifies the package and type of the EJB home interface. Alternatively, use the <local-home> subelement for EJB local interfaces.

  • The <remote> subelement specifies the package and type of the EJB remote interface. Alternatively, use the <local> subelement for EJB local interfaces.

These values are reflected in attribute values of the EJB tags.

See the Oracle Application Server Containers for J2EE Enterprise JavaBeans Developer's Guide for additional information about EJB development and configuration.

EJB Tag Descriptions

This section provides syntax and attribute descriptions for the OC4J EJB tags. Be aware of the following requirements:

  • Verify that the file ojsputil.jar is installed and in your classpath. This file is provided with OC4J, in the "well-known" tag library directory.

  • The tag library descriptor, ejbtaglib.tld, must be available to the application, and any JSP page using the library must have an appropriate taglib directive. In an Oracle Application Server installation, the TLD is in ojsputil.jar. The uri value for ejbtaglib.tld is the following:

    http://xmlns.oracle.com/j2ee/jsp/tld/ojsp/ejbtaglib.tld
    
    

You can refer to the Oracle Application Server Containers for J2EE Support for JavaServer Pages Developer's Guide for information about taglib directives, the well-known tag library directory, TLD files, and the meaning of uri values.


Notes:

  • The prefix "ejb:" is used in the tag syntax here. This is by convention but is not required. You can specify any desired prefix in your taglib directive.

  • See "Tag Syntax Symbology and Notes" for general information about tag syntax conventions in this manual.


The following sections provide information about the EJB tags:

When first creating an EJB instance, you will have to use a useHome tag to create a home interface instance. Then use the following as appropriate:

  • To create a single EJB instance: a useBean tag, and either the useBean tag value attribute or a nested createBean tag

  • To create a collection of EJB instances and iterate through them (more typical for entity beans): an iterate tag

After an EJB instance is created, it is placed in the appropriate scope object. You will need only a useBean tag to access it subsequently.

EJB useHome Tag

The useHome tag looks up the home interface for the EJB and creates an instance of it.

Syntax

<ejb:useHome id = "home_instance_name" 
             type = "home_interface_type" 
             location = "home_lookup_name" 
           [ local = "true" | "false" ] />

This tag uses no body.

Attributes

  • id (required): Specify a name for the home interface instance. This can be for either a local or remote home interface, depending on the setting of the local attribute. The instance is accessible from the start-tag to the end of the page.

  • type (required): This is for the name (Java type) of the home interface.

  • location (required): This is a JNDI name used to look up the home interface of the desired EJB within the application.

  • local: Set this to "true" to use the local home interface. The default value is "false", to use the remote home interface. If local="true" for the useHome tag, this must also be the case for the useBean tag.

Example

<ejb:useHome id="aomHome" type="com.acme.atm.ejb.AccountOwnerManagerHome"
             location="java:comp/env/ejb/accountOwnerManager" />

EJB useBean Tag

Use the EJB useBean tag for instantiating and using the EJB. The id, type, and scope attributes are used as in a standard jsp:useBean tag that instantiates a regular JavaBean.

You can use one of two mechanisms when you first instantiate the EJB:

  • The value attribute

or:

  • A nested EJB createBean tag

When using a nested createBean tag, the EJB instance is implicitly returned into the value attribute of the parent useBean tag. Once the EJB is instantiated, value attributes and nested createBean tags are unnecessary for subsequent useBean tags using the same EJB instance.


Note:

See "EJB iterate Tag" for how to use a collection of EJB instances.

Syntax

<ejb:useBean id = "EJB_instance_name" 
             type = "EJB_class_name" 
           [ value = "<%=Object%>" ]
           [ scope = "page" | "request" | "session" | "application" ]  
           [ local = "true" | "false" ] >

... nested createBean tag for first instantiation, if no value attribute ...

</ejb:useBean>
Attributes

  • id (required): Specify an instance name for the EJB.

  • type (required): Specify the class name for the EJB.

  • value: When first instantiating the EJB, if you do not use a nested createBean tag, you can use the value attribute to return an EJBObject instance to narrow. This is a mechanism for instantiating the EJB.

  • scope: Specify the scope of the EJB instance. The default scope setting is "page".

  • local: Set this to "true" to use the local home interface. The default value is "false", to use the remote home interface. If local="true" for the useBean tag, this must also be the case for the useHome tag.


Note:

You cannot use local="true" if scope="session" in a distributable application.

Example

This example shows the use of an EJB that has already been instantiated.

<ejb:useBean id="bean" type="com.acme.MyBean" scope="session" />

EJB createBean Tag

For first instantiating an EJB, if you do not use the value attribute of the EJB useBean tag, you must nest an EJB createBean tag within the useBean tag to do the work of creating the EJB instance. This will be an EJBObject instance. The instance is implicitly returned into the value attribute of the parent useBean tag.

Syntax

<ejb:createBean instance = "<%=Object%>" />

This tag uses no body.

Attributes

  • instance (required): This is to return the EJB, a created EJBObject instance.

Example

In this createBean tag, the create() method of the EJB home interface instance creates an instance of the EJB.

<ejb:useBean id="bean" type="com.acme.MyBean" scope="session"> 
     <ejb:createBean instance="<%=home.create()%>" /> 
</ejb:useBean>

EJB iterate Tag

Use this tag to iterate through a collection of EJB instances. This is more typical for entity beans, because standard finder methods for entity beans return collections.

In the start-tag, obtain the collection through finder results from the home interface. In the tag body, iterate through the collection as appropriate.


Note:

See "EJB useBean Tag" for how to use a single EJB instance.

Syntax

<ejb:iterate id = "EJB_instance_name" 
             type = "EJB_class_name" 
             collection = "<%=Collection%>" 
           [ max = "<%=Integer%>" ] >

... body ...

</ejb:iterate>

The body is evaluated once for each EJB in the collection.

Attributes

  • id (required): This is an iterator variable, the EJB instance name for each iteration.

  • type (required): This is the EJB class name.

  • collection (required): This is to return the EJB collection.

  • max: Optionally specify a maximum number of beans to iterate through.

Example

<ejb:iterate id="account" type="com.acme.atm.ejb.Account"
             collection="<%=accountManager.getOwnerAccounts()%>"
             max="100"> 
     <jsp:getProperty name="account" property="id" /> 
</ejb:iterate>

EJB Tag Examples

This section provides examples of EJB tag usage, one using a session bean and one using an entity bean.

EJB Tag Session Bean Example

This example relies on the following configuration in the application web.xml file:

<ejb-ref>
   <ejb-ref-name>ejb/DemoSession</ejb-ref-name>
   <ejb-ref-type>Session</ejb-ref-type>
   <home>ejbdemo.DemoSessionHome</home>
   <remote>ejbdemo.DemoSession</remote>
</ejb-ref>

Here is the sample code:

<%@ page import="ejbdemo.*" %> 
<%@ taglib uri="http://xmlns.oracle.com/j2ee/jsp/tld/ojsp/ejbtaglib.tld"
           prefix="ejb" %> 
<html> 
<head> <title>Use EJB from JSP</title> </head> 
<body> 

<ejb:useHome id="home" type="ejbdemo.DemoSessionHome"
             location="java:comp/env/ejb/DemoSession" /> 
<ejb:useBean id="demo" type="ejbdemo.DemoSession" scope="session" > 
    <ejb:createBean instance="<%=home.create()%>" /> 
</ejb:useBean> 
<heading2>      Enterprise Java Bean:  </heading2> 
 <p><b> My name is "<%=demo.getName()%>". </b></p> 
</body> 
</html> 

This sample code accomplishes the following:

  • It creates the home instance of the EJB home interface. Note that the type value of the useHome tag matches the value of the <home> subelement of the <ejb-ref> element in the web.xml file. Also, the location value of useHome reflects the value of the <ejb-ref-name> subelement of the <ejb-ref> element.

  • It uses the home.create() method to create the demo instance of the EJB. Note that the type value of the useBean tag matches the value of the <remote> subelement of the <ejb-ref> element in the web.xml file.

  • It uses the demo.getName() method to print a user name.

EJB Tag Entity Bean Example

This example relies on the following configuration in the application web.xml file:

<ejb-ref>
   <ejb-ref-name>ejb/DemoEntity</ejb-ref-name>
   <ejb-ref-type>Entity</ejb-ref-type>
   <home>ejbdemo.DemoEntityHome</home>
   <remote>ejbdemo.DemoEntity</remote>
</ejb-ref>

Here is the sample code:

<%@ page import="ejbdemo.*" %> 
<%@ taglib uri="http://xmlns.oracle.com/j2ee/jsp/tld/ojsp/ejbtaglib.tld"
           prefix="ejb" %> 
<html> 
<head> <title>Iterate over EJBs from JSP</title> </head> 
<body> 

<ejb:useHome id="home" type="ejbdemo.DemoEntityHome"
             location="java:comp/env/ejb/DemoEntity" /> 
<% int i=0; %> 
<ejb:iterate id="demo" type="ejbdemo.DemoEntity"
             collection="<%=home.findAll()%>" max="3" > 
<li> <heading2> Bean #<%=++i%>:  </heading2> 
 <b> My name is "<%=demo.getName()+"_"+ demo.getId()%>". </b> </li> 
</ejb:iterate> 
</body> 
</html> 

This sample code accomplishes the following:

  • It creates the home instance of the EJB home interface. Note that the type value of the useHome tag matches the value of the <home> subelement of the <ejb-ref> element in the web.xml file. Also, the location value of useHome reflects the value of the <ejb-ref-name> subelement of the <ejb-ref> element.

  • It uses the home.findAll() method to return a collection of EJBs. Note that the type value in the iterate tag matches the value of the <remote> subelement of the <ejb-ref> element in the web.xml file.

  • It iterates through the collection, always using demo for the current instance, and using the demo.getName() and demo.getId() methods to output information from each EJB.

General Utility Tags

OC4J provides miscellaneous utility tags to perform a number of operations. The following sections contain details about the tags:

Note the following requirements for the utility tags:

You can refer to the Oracle Application Server Containers for J2EE Support for JavaServer Pages Developer's Guide for information about taglib directives, the well-known tag library directory, TLD files, and the meaning of uri values.


Notes:

  • The prefix "util:" is used in the tag syntax here. This is by convention but is not required. You can specify any desired prefix in your taglib directive.

  • See "Tag Syntax Symbology and Notes" for general information about tag syntax conventions in this manual.


Display Tags

The following sections document syntax and attributes of the display tags:

Utility displayCurrency Tag

This tag displays a specified amount of money, formatted as currency appropriate for the locale. If no locale is specified, then the request object will be searched for a locale. If none is found there, the system default locale is used.

Syntax

<util:displayCurrency amount = "<%=Double%>"
                    [ locale = "<%=Locale%>" ] />

This tag uses no body.

Attributes

  • amount (required): Specify the amount to format.

  • locale: Optionally specify a locale, as a java.util.Locale instance.

Example

<util:displayCurrency amount="<%=account.getBalance()%>"
                      locale="<%=account.getLocale()%>" />

Utility displayDate Tag

This tag displays a specified date, formatted appropriately for the locale. If no locale is specified, the system default locale is used.

Syntax

<util:displayDate date = "<%=Date%>" 
                [ locale = "<%=Locale%>" ] />

This tag uses no body.

Attributes

  • date (required): Specify the date to format, as a java.util.Date instance.

  • locale: Optionally specify a locale, as a java.util.Locale instance.

Example

<util:displayDate date="<%=account.getDate()%>"
                  locale="<%=account.getLocale()%>" />

Utility displayNumber Tag

This displays the specified number appropriately for the locale and optionally in the specified format. If no locale is specified, the system default locale is used.

Syntax

<util:displayNumber number = "<%=Double%>"
                  [ locale = "<%=Locale%>" ]
                  [ format = "<%=Format%>" ] />

This tag uses no body.

Attributes

  • number (required): Specify the number to format.

  • locale: Optionally specify the locale, as a java.util.Locale instance.

  • format: Optionally specify a format, as a java.text.Format instance.

Example

<util:displayNumber number="<%=shoe.getSize()%>" />

Miscellaneous Utility Tags

The following sections document syntax and attributes of the general utility tags:

Utility iterate Tag

Use this tag to iterate through a collection. Obtain the collection in the start-tag and iterate through the collection in the body.

Syntax

<util:iterate id = "instance_name" 
              type = "class_name" 
              collection = "<%=Collection%>" 
            [ max = "<%=Integer%>" ] >

... body ...

</util:iterate>

The body is evaluated once for each element in the collection.

Attributes

  • id (required): This is an iterator variable, the instance name for each iteration.

  • type (required): This is the class name; the collection is a set of instances of this type.

  • collection (required): This is the collection itself.

  • max: Optionally specify a maximum number of elements to iterate through.

Example

<util:iterate id="contact" type="com.acme.connections.Contact"
              collection="<%=company.getContacts()%>" >
     <jsp:getProperty name="contact" property="name"/>
</util:iterate>

Utility ifInRole Tag

Use this tag to evaluate the tag body and include it in the body of the JSP page, depending on whether the user is in the specified application role. The tag handler executes the isUserInRole() method of the request object.

The concept of "role" is according to the servlet specification. Roles are defined in <role> elements in the application web.xml file.

Syntax

<util:ifInRole role = "<%=String%>" 
             [ include = "true" | "false" ] >

   ... body to include ...

</util:ifInRole>
Attributes

  • role (required): Specify the role to check, to see if the user included in this role.

  • include: Use a "true" setting (the default) to include the body only if the user is in the role. Use a "false" setting to include the body only if the user is not in the role.

Example

<util:ifInRole role="users" include="true"> 
     Logged in as <%=request.getRemoteUser()%><br>
     <form action="logout.jsp">
     <input type="submit" value="Log out"><br>
     </form> 
</util:ifInRole>
<util:ifInRole role="users" include="false"> 
     <form method="POST">
     Username: <input name="j_username" type="text"><br>
     Password: <input name="j_password" type="password"><br>
     <input type="submit" value="Log in">
     </form>
</util:ifInRole> 

Utility lastModified Tag

This tag displays the date of the last modification of the current file, appropriately formatted for the locale. If no locale is specified, then the request object will be searched for a locale. If none is found there, the system default locale is used.

Syntax

<util:lastModified 
             [ locale = "<%=Locale%>" ] />

This tag uses no body.

Attributes

  • locale: Optionally specify the locale, as a java.util.Locale instance.

Example

<util:lastModified />