Skip Headers

Oracle9iAS Containers for J2EE JSP Tag Libraries and Utilities Reference
Release 2 (9.0.2)

Part Number A95883-01
Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Go to previous page Go to next page

8
JSP Utilities and Utility Tags

This chapter documents a variety of general utility features available with OC4J for use in JSP pages, including the following:

These features are implemented according to JSP and servlet standards and are generally portable to other JSP environments.

JSP Event-Handling--JspScopeListener

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.

This section covers the following topics:

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.

Properties of the JspScopeEvent object include the following:

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.

For a complete sample, refer to the OC4J demos.

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.

This section covers the following topics:

Requirements for JspScopeListener

The JspScopeListener implementation requires the following:

Runtime and Tag Implementations to Support Page Scope

For OC4J and JServ environments, there is support for page scope through an Oracle-specific runtime implementation. No configuration or special steps on your part are required.

For portability to other environments, there is also an implementation to support page scope through a special 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 of logic any
      JspScopeListener stored in page scope
      This tag is not needed on
      JServ or OC4J.
   </info>
</tag>

Here is an example of its use:

<%@ taglib uri="/WEB-INF/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 of logic any
      JspScopeListener stored in page scope
      This tag is not needed on JServ
      or 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 description file. An appropriate taglib directive is shown in the preceding example (the "jml" prefix is typical). 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. 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 may 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 2.3 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, 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--first a JSP page and accompanying JavaBean, and 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 it is entered into the application-level catalog hashtable, and the book count is incremented.

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
       }
    }
}

Mail JavaBean and Tag

It is often useful to be able to send e-mail messages from a Web application, based on Web site status or user actions. Sun Microsystems has specified a platform-independent and protocol-independent framework for this through its javax.mail package and subpackages, known as the JavaMail API.

For further convenience, Oracle supplies a JavaBean and JSP custom tag, based on the JavaMail API, to use in providing e-mail functionality through your servlets or JSP pages. The bean and tag, as with other JavaBeans and custom tags supplied with OC4J, are implemented according to JSP and servlet standards.

This section, organized as follows, describes the mail JavaBean and tag:

For more information about the JavaMail API, you can refer to the following Sun Microsystems Web site:

http://java.sun.com/products/javamail/1.2/docs/javadocs/index.html

General Considerations for the Mail JavaBean and Tag

Be aware of the following points, which apply to use of either the mail JavaBean (SendMailBean) or the mail tag (sendMail):

SendMailBean Description

The oracle.jsp.webutil.email.SendMailBean JavaBean is supplied with OC4J to support e-mail functionality from servlet or JSP applications. To use it in a JSP page, you can instantiate it through the standard jsp:useBean tag. (However, for JSP applications, you may want to use the sendMail tag instead--see "The sendMail Tag Description".)

SendMailBean Requirements

To use SendMailBean, verify that the files ojsputil.jar, mail.jar, and activation.jar are installed and in your classpath. These files are supplied with OC4J.

When you use SendMailBean in your code, you must provide the following:

All other SendMailBean attributes are optional.

SendMailBean Method Descriptions

This section lists and describes SendMailBean methods to send mail messages, close mail sessions, and set or get bean attributes.


Note:

To comply with the JavaBean specification, SendMailBean has a no-argument constructor.


Here are the public SendMailBean methods:

The sendMail Tag Description

As a convenience for JSP developers, OC4J supplies the sendMail tag to provide e-mail functionality for a JSP page. This section describes the tag, including the following topics:

To use the sendMail tag, verify that the files ojsputil.jar, mail.jar, and activation.jar are installed and in your classpath. These files are supplied with OC4J.

In the current implementation, the sendMail tag has its own TLD file, email.tld, located in the OC4J /j2ee/tlds directory. To use the tag, you must include a taglib directive, such as the following, to reference this TLD file in your JSP page:

<%@ taglib uri="/WEB-INF/email.tld" prefix="mail" %>

The sendMail Tag Syntax

The sendMail tag has the following syntax:

<mail:sendMail host = "SMTP_host_name" | session = "JavaMail_session_name" 
               sender = "sender_address"
               recipient = "primary_recipient_IDs"
             [ cc = "cc_recipient_IDs" ]
             [ bcc = "bcc_recipient_IDs" ] 
             [ subject = "subject_line" ]
             [ contentType = "MIME_type; [charset=charset]" ]
             [ contentEncoding = "B"|"base64"|"Q"|"quoted-printable"|
                                 "7bit"|"8bit" ] >
...
E-mail body
...
</mail:sendMail>


Notes:

  • The sender and recipient attributes are required, and either the host or session attribute is required.

  • Multiple recipients, cc targets, or bcc targets are space-separated or comma-separated.

  • The e-mail body can contain JSP syntax, which will be processed by the JSP translator.

  • Attributes used by the tag are typically input by the user in form fields.

  • The prefix "mail:" 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 sendMail Tag Attribute Descriptions

The sendMail tag supplies the following attributes:

Sample Application for sendMail Tag

This sample application illustrates use of the sendMail tag. During the first execution cycle through the page, before the user has specified the sender (or anything else), the HTML form is displayed for user input. During the next execution cycle through the page, after the user has sent the input, the sendMail tag is executed. This page also uses an error page, error.jsp (shown below), to display any exceptions that are thrown.

<%@ page language="java" errorPage="error.jsp" %>
<%@ taglib uri="/WEB-INF/email.tld" prefix="mail" %>
<%
if (request.getParameter("sender")==null) {
%>
<HTML>
<HEAD><TITLE>SendMail Sample</TITLE></HEAD>
<FORM METHOD=post>
<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0 WIDTH="20%">
<TR><TD>Host:</TD><TD><INPUT TYPE="text" name="host" ></TD></TR>
<TR><TD>From:</TD><TD><INPUT TYPE="text" name="sender" ></TD></TR>
<TR><TD>To:</TD><TD><INPUT TYPE="text" name="recipient"  ></TD></TR>
<TR><TD>Cc:</TD><TD><INPUT TYPE="text" name="cc" ></TD></TR>
<TR><TD>Bcc:</TD><TD><INPUT TYPE="text" name="bcc" ></TD></TR>
<TR><TD>Subject:</TD><TD><INPUT TYPE="text" name="subject"
VALUE="Hi"></TD></TR>
</TABLE><br>
<TEXTAREA name="body" ROWS=4 COLS=30>"How are you!"</TEXTAREA><br><br>
<INPUT TYPE="submit" value="Send">
</FORM>
<%
}
else{
%>
<BODY BGCOLOR="#FFFFFF">
<P>Result:
       <HR>
       <mail:sendMail host='<%=request.getParameter("host")%>'
             sender='<%=request.getParameter("sender")%>'
             recipient='<%=request.getParameter("recipient")%>'
             cc='<%=request.getParameter("cc")%>'
             bcc='<%=request.getParameter("bcc")%>'
             subject='<%=request.getParameter("subject")%>'>
             <%=request.getParameter("body")%>
       </mail:sendMail>
Sent out Successfully!
       <HR>
</BODY>
<%
}
%>
</HTML>

Here is the error page, error.jsp:

<%@ page language="java" isErrorPage="true"%>
<HTML>
Error: <%= exception.getMessage() %>
</HTML>

When you run this application, you will initially see the following default screen:

Text description of smaildef.gif follows.

Text description of the illustration smaildef.gif

And here is sample user input for a message from brian.wright@oracle.com to blodney.treehut@oracle.com through the host gmail.oraclecorp.com:

Text description of smailtst.gif follows.

Text description of the illustration smailtst.gif

File-Access JavaBeans and Tags

OC4J provides a portable tag library and JavaBeans that add convenient file upload and file download functionality for JSP pages and servlets. Files can be uploaded to or downloaded from a file system or database.

This section documents these features and is organized as follows:

Overview of OC4J File-Access Functionality

Developers have the option of using either custom tags or JavaBeans to program applications that allow users to upload or download files. In either case, the application is presumably programmed so that users specify through the browser where files come from on the client system for uploading, or where they go to on the client system for downloading. For JSP pages for uploading, OC4J supplies a convenience tag, httpUploadForm, to create a form for this purpose.

For processing an upload, including specifying the destination file system or database location, use the HttpUploadBean JavaBean or the httpUpload tag. For processing a download, including specifying the source file system or database location, use HttpDownloadBean or the httpDownload tag. The beans extend HttpFileAccessBean, which is not intended for public use. All of the beans are in the oracle.jsp.webutil.fileaccess package.

Overview of File Uploading

For user specification in a JSP page of where uploaded files will come from, you can use the httpUploadForm tag to create a form. This tag lets users select the files for uploading, and creates the necessary multipart HTTP request. You also have the option of using a standard HTML form to create the request.

Use the HttpUploadBean JavaBean or the httpUpload tag to receive and process the multipart form-encoded data stream and write the files to the appropriate location, either in the file system or a database. There is functionality to let you decide whether previous data will be overwritten if the target file or database row already exists.


Note:

The maximum file size for any upload is 2 GB.


File System Destination

If the destination is in a file system, you must provide a properties file that designates a base directory. The properties file must be named fileaccess.properties, must be located in the /WEB-INF directory of your application, and must have a fileaccess.basedir entry such as the following (this example is for a Microsoft Windows system):

fileaccess.basedir=C:\tmp

Under the base directory, there should be subdirectories as appropriate--for example, a subdirectory for each authorized user. Destination subdirectories under the base directory must be specified through an attribute of the upload bean or tag. All directories and subdirectories must already exist and be writable; they cannot be created or made writable through OC4J functionality.

Database Destination

If the destination is in a database, you can optionally use a default table, fileaccess, that you create through the supplied fileaccess.sql script, or you can use any other previously existing table containing the required column types. In either case, you must provide a connection to the database, as an instance of either oracle.jsp.dbutil.ConnBean or the standard java.sql.Connection. You can provide a ConnBean instance either explicitly, or, in a JSP page, implicitly as a result of nesting the httpUpload tag inside a dbOpen tag. (For information about the ConnBean JavaBean and dbOpen tag, see Chapter 4, "Data-Access JavaBeans and Tags".)

It is also required that you specify a destination through an attribute of the upload bean or tag. The destination is simply a Java string value that will be placed in the prefix column of the database table. The prefix is equivalent to a file system path.

File data is written to a database as either a BLOB or a CLOB (specify which through an upload bean or tag attribute).

If you do not use the default fileaccess table, you must use attributes of the upload bean or tag to specify the database table name and the names of the columns that will contain the file data, the file prefix, and the file name. Any other table you use must adhere to the pattern of fileaccess, as follows:

Security Considerations for Uploading

For uploading to a database, the database table does not have a column to indicate a particular authorized user for any given file. Therefore, without precaution, each user can see files that were uploaded by other users, without having to know the file prefixes. To prevent this, you can prepend an appropriate user name to each prefix.

Overview of File Downloading

Use the HttpDownloadBean JavaBean or the httpDownload tag as follows:

There is also functionality to specify whether you want recursive downloading, where files in subdirectories or with additional database prefix information will also be available for download. For database downloading, a prefix is equivalent to a file system path and can be used to group files into a hierarchy. As an example of recursive downloading from a database, assume you have specified /user as the prefix. Recursive downloading would find matches for files with any prefixes starting with /user, such as /user/bill and /user/mary, and also such as /user1, /user2, /user1/tom, and /user2/susan.

For downloading files from a file system, use the mechanism described in "Overview of File Uploading"--use the fileaccess.properties file to specify a base directory, and use attributes in the download bean or tag to specify the rest of the file path.

For downloading files from a database, as with uploading files to a database, you must provide an instance of oracle.jsp.dbutil.ConnBean or java.sql.Connection. In addition, if you are not using the default fileaccess table (that you can create using the supplied fileaccess.sql script), you must provide all the necessary information about the database table and columns. Specify this information through attributes of the download bean or tag.

The actual downloading of the files is accomplished by DownloadServlet, supplied with OC4J. In using the download tag, you specify the path of this servlet through a tag attribute. For a file system source, hyperlinks are automatically created to the servlet so that the user can click on a link for each file in order to download the file. For a database source, the servlet will fetch the selected CLOB or BLOB data that forms the file contents. (See "The Download Servlet".)

Security Considerations for Downloading

For downloading, you may want to consider limiting the users' ability to see what is in the source (server-side) file system or database. Without precaution, the following scenarios are possible:

If this is of concern, you can consider protective measures such as the following:

File Upload and Download JavaBean and Class Descriptions

This section describes attributes and methods of the file upload and download JavaBeans provided with OC4J--HttpUploadBean and HttpDownloadBean, respectively.

There is also brief discussion of DownloadServlet, provided with OC4J to perform the actual file downloading, and the class FileAccessException that is used by the file-access JavaBeans for exceptions relating to file uploads and downloads.

To comply with the JavaBean specification, the file upload and download JavaBeans provide no-argument constructors.


Note:

To use the file upload and download JavaBeans, verify that the file ojsputil.jar is installed and in your classpath. This file is provided with OC4J.


The HttpUploadBean

The oracle.jsp.webutil.fileaccess.HttpUploadBean JavaBean provides numerous setter methods for specifying information used for the uploading. It also includes most corresponding getter methods. Once you have set all the required and appropriate attributes, use the upload() method to perform the upload. There is also a method to display the names of the files that were uploaded, typically so you can provide an informative message to the browser.

HttpUploadBean, as with HttpDownloadBean, extends HttpFileAccessBean, which itself is not intended for public use.

See "Overview of File Uploading" for related information.

Summary of Required Attributes

The following list summarizes required attributes for HttpUploadBean:

In addition, for an upload to a file system, you must call the setBaseDir() method to provide a servlet context and HTTP request object so that the bean can find the fileaccess.properties file that specifies the base directory.

Methods

Here are descriptions of the public methods of HttpUploadBean.


Note:

Many of the attributes and setter methods for HttpUploadBean are the same as for HttpDownloadBean.


Example:

This example uses a plain HTML form to specify a file to upload to a file system, then uses a JSP page that employs HttpUploadBean for the upload.

Here is the HTML form, which specifies beanUploadExample.jsp for its action and will generate the multipart upload stream.

<html><body>
<form action="beanUploadExample.jsp" ENCTYPE="multipart/form-data" method=POST>
<br> File to upload: <INPUT TYPE="FILE" NAME="File" SIZE="50" MAXLENGTH="120" >
<br><INPUT TYPE="SUBMIT" NAME="Submit" VALUE="Send"> </form>
</body></html>

And here is the beanUploadExample.jsp page.

<%@ page language="java" 
         import="java.util.*, oracle.jsp.webutil.fileaccess.*" %>
<html><body>
<% String userdir = "fileaccess"; %>   // user's part of the upload directory
<jsp:useBean id="upbean" 
   class="oracle.jsp.webutil.fileaccess.HttpUploadBean" >
   <jsp:setProperty name="upbean" property="destination" value="<%= userdir %>" 
/>
</jsp:useBean>
<%   upbean.setBaseDir(application, request);
         upbean.upload(request); 
         Enumeration fileNames = upbean.getFileNames();
         while (fileNames.hasMoreElements()) { %>
              <br><%= (String)fileNames.nextElement() %>
  <% } %>
<br>Done!
</body></html>

The HttpDownloadBean

The oracle.jsp.webutil.fileaccess.HttpDownloadBean JavaBean provides numerous setter methods for specifying information used for downloading. It also includes most corresponding getter methods. Once you have set all the required and appropriate attributes, use the listFiles() method to list the files available for download. The actual downloading is accomplished through DownloadServlet, supplied with OC4J, one file at a time. See "The Download Servlet".


Note:

You must construct the URL for DownloadServlet in your application code.


HttpDownloadBean, as with HttpUploadBean, extends HttpFileAccessBean, which itself is not intended for public use.

See "Overview of File Uploading" for related information.

Summary of Required Attributes

The following list summarizes required attributes for HttpDownloadBean:

In addition, for a download from a file system, you must call the setBaseDir() method to provide a servlet context and HTTP request object so that the bean can find the fileaccess.properties file that specifies the base directory.

Methods

Here are descriptions of the public methods of HttpDownloadBean.


Note:

Many of the attributes and setter methods for HttpDownloadBean are the same as for HttpUploadBean.


Example

This example is a JSP page that uses HttpDownloadBean for a download from a file system. Note that the page must construct the URL for the download servlet.

<%@ page language="java" import="java.util.*, oracle.jsp.webutil.fileaccess.*" 
%>
<html><body>
<% String servletPath = "/servlet/download/";  // path to the download servlet
   String userDir = "fileaccess/";   // user part of  download directory
%>
<jsp:useBean id="dbean" 
   class="oracle.jsp.webutil.access.HttpDownloadBean" >
   <jsp:setProperty name="dbean" property="source" value='<%=userDir %>' />
</jsp:useBean>
<%    dbean.setBaseDir(application, request);   
          dbean.listFiles(request); %>
The following files were found:
<%   Enumeration fileNames = dbean.getFileNames(); 
         while (fileNames.hasMoreElements()) { 
                String name = (String)fileNames.nextElement();  %>
               <br><a href="<%= servletPath + name %>" > <%= name %></a>
<%    } %>
<br>Done!
</body></html>

The Download Servlet

To use download functionality, through either HttpDownloadBean or the httpDownload tag, you must have the class oracle.jsp.webutil.fileaccess.DownloadServlet available in your Web server.

Its mapping in your Web server must be reflected in your servlet path settings, either through the servletPath attribute if you use the httpDownload tag, or in your application code if you use HttpDownloadBean. For an example of how to configure it in your Web server, see the /WEB-INF/web.xml file for the OC4J demos.

The OC4J demos, for example, expect to find DownloadServlet mapped to the servlet name download with the context path /j2ee/servlet (the context root of the OC4J default Web application). That is, it must be accessible by the following relative path, unless you edit web.xml:

/j2ee/servlet/download

FileAccessException Class

The oracle.jsp.webutil.fileaccess.FileAccessException class is a convenience class supplied with OC4J for file-access exception-handling. It wraps the functionality of the standard java.sql.SQLException and java.io.IOException classes. It handles exceptions from either of the file-access beans in addition to handling SQL and I/O exceptions.

File Upload and Download Tag Descriptions

For file uploading, OC4J supplies the httpUpload tag. This tag, in turn, uses HttpUploadBean. For convenience, you can also use the httpUploadForm tag in programming the form through which users specify the files to upload, or you can code the form manually.

For file downloading, OC4J provides the custom httpDownload tag.This tag uses HttpDownloadBean. This section describes these tags and their attributes.

To use the file upload and download tags, verify that the file ojsputil.jar is installed and in your classpath. This file is provided with OC4J.

The tag library description file for the file access tags is fileaccess.tld, located in the OC4J /j2ee/tlds directory. To use the library, you will need a taglib directive such as the following:

<%@ taglib uri="/WEB-INF/fileaccess.tld" prefix="fileaccess" %>


Notes:

  • The prefix "fileaccess:" 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 httpUploadForm Tag

For convenience, you can use the httpUploadForm tag to create a form in your application, using multipart encoded form data, that allows users to specify the files to upload.

Syntax

<fileaccess:httpUploadForm formsAction = "action" 
                         [ maxFiles = "max_number" ]
                         [ fileNameSize = "file_input_box_num_chars" ]
                         [ maxFileNameSize = "max_file_name_num_chars" ]
                         [ includeNumbers = "true" | "false" ]
                         [ submitButtonText = "button_label_text" ] />


Note:

The httpUploadForm tag can optionally use a body. For example, the body might consist of a user prompt.


Attributes

The httpUpload Tag

This tag wraps the functionality of the HttpUploadBean JavaBean, paralleling its attributes. See "Overview of File Uploading" and "The HttpUploadBean" for related information.

Syntax

<fileaccess:httpUpload destination = "dir_path_or_prefix"
                 [ destinationType = "filesystem" | "database" ]
                 [ connId = "id" ]
                 [ scope = "request" | "page" | "session" | "applicaton" ]
                 [ overwrite = "true" | "false" ]
                 [ fileType = "character" | "binary" ]
                 [ table = "table_name" ]
                 [ prefixColumn = "column_name" ]
                 [ fileNameColumn = "column_name" ]
                 [ dataColumn = "column_name" ] />


Note:

For uploads to a file system, the base directory is automatically retrievable by the tag handler from the JSP page context.


Attributes

Example

This example has a page that uses the httpUploadForm tag to create the HTML form for specifying files to upload. The httpUploadForm tag specifies httpUploadExample.jsp as its forms action. The httpUploadExample.jsp page uses the httpUpload tag to upload to the default fileaccess table in a database.

Here is the page for the HTML form:

<%@ page language="java" import="java.io.*"  %>
<%@ taglib uri="/WEB-INF/fileaccess.tld" prefix="upload" %>
<html> <body>
<fileaccess:httpUploadForm 
      formsAction="httpUploadExample.jsp"
      maxFiles='<%= request.getParameter("MaxFiles") %>'
      includeNumbers="true"  fileNameSize="50"  maxFileNameSize="120" >
          <br> File:
</fileaccess:httpUploadForm>
</body> </html> 

And following is the httpUploadExample.jsp page. Note that the httpUpload tag gets its database connection as a result of being inside a dbOpen tag. Also note that setconn.jsp is used to obtain the connection, if necessary. See "setconn.jsp".

<%@ page language="java" %>
<%@ taglib uri="/WEB-INF/fileaccess.tld" prefix="upload" %>
<%@ taglib uri="/WEB-INF/sqltaglib.tld" prefix="sql" %>
<% String connStr=request.getParameter("connStr"); // get the connection string
       if (connStr==null) {  connStr=(String)session.getValue("connStr"); }
       else {  session.putValue("connStr",connStr); }
       if (connStr==null) { %>
           <jsp:forward page="setconn.jsp" />
<% } %>
<html><body>
<sql:dbOpen URL="<%= connStr %>" user="scott" password="tiger" >
   <fileaccess:httpUpload  destinationType = "database"
                           destination="tagexample" />
</sql:dbOpen>
Done! </body></html>

The httpDownload Tag

This tag wraps the functionality of the HttpDownloadBean JavaBean, paralleling its attributes. See "Overview of File Downloading" and "The HttpDownloadBean" for related information.

Syntax

<fileaccess:httpDownload servletPath = "path"
                   source = "dir_path_or_prefix"
                 [ sourceType = "filesystem" | "database" ]
                 [ connId = "id" ]
                 [ scope = "request" | "page" | "session" | "applicaton" ]
                 [ recurse = "true" | "false" ]
                 [ fileType = "character" | "binary" ]
                 [ table = "table_name" ]
                 [ prefixColumn = "column_name" ]
                 [ fileNameColumn = "column_name" ]
                 [ dataColumn = "column_name" ] />


Notes:

  • The httpDownload tag can optionally use a body. For example, the body might consist of a user prompt.

  • For downloads from a file system, the base directory is automatically retrievable by the tag handler from the JSP page context.


Attributes

Example

This example is a JSP page that uses the httpDownload tag to download from the default fileaccess table of a database. The tag body content ("<br>:") will be output before each file name in the list of files available for download. Note that you must specify the DownloadServlet servlet path in the httpDownload tag; the tag handler will use it in constructing the URL to DownloadServlet, which performs the actual downloading.

<%@ page language="java" %>
<%@ taglib uri="/WEB-INF/fileaccess.tld" prefix="download" %>
<%@ taglib uri="/WEB-INF/sqltaglib.tld" prefix="sql" %>
<% String connStr=request.getParameter("connStr");
       if (connStr==null) { connStr=(String)session.getValue("connStr");}
       else { session.putValue("connStr",connStr);}
       if (connStr==null) { %>
          <jsp:forward page="setconn.jsp" />
<% } %>
<html> <body>
<% String servletPath = "/servlet/download/"; %>
<sql:dbOpen URL="<%= connStr %>" user="scott" password="tiger" >
<fileaccess:httpDownload sourceType = "database" 
            source="tagexample" servletPath = `<%= servletPath %>' >
   <br>:
</fileaccess:httpDownload>
</sql:dbOpen>
<br>Done!
</body> </html>

EJB Tags

OC4J provides a custom tag library to simplify the use of Enterprise JavaBeans in JSP pages.

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 standard jsp:useBean tag for invoking a regular JavaBean.

The rest of this section is organized as follows:

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 are used according to the Sun Microsystems Servlet Specification, Version 2.2 (or higher). Briefly, this is as follows:

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

EJB Tag Descriptions

This section provides syntax and attribute descriptions for the OC4J EJB tags.

To use the EJB tags, verify that the file ojsputil.jar is installed and in your classpath. This file is provided with OC4J.

The tag library description file for the EJB tags is ejbtaglib.tld, located in the OC4J /j2ee/tlds directory. To use the library, you will need a taglib directive such as the following:

<%@ taglib uri="/WEB-INF/ejbtaglib.tld" prefix="ejb" %>


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 tags are available:

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

After an EJB instance is created, it is placed in the appropriate scope object, and 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" />

This tag uses no body.

Attributes

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:

or:

When using a 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" ]  >

... nested createBean tag for first instantiation (if no value attribute) ...

</ejb:useBean>

Attributes

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

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:

  • This tag has the same semantics as the more general iterate utility tag, discussed in "Utility iterate Tag". It is copied into the EJB tag library for convenience.

  • 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

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 use 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="/WEB-INF/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 accomplishes the following:

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="/WEB-INF/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 accomplishes the following:

General Utility Tags

OC4J provides a number of miscellaneous utility tags to perform various operations. This section documents these tags and is organized as follows:

To use the utility tags, verify that the file ojsputil.jar is installed and in your classpath. This file is provided with OC4J.

The tag library description file for the utility tags is utiltaglib.tld, located in the OC4J /j2ee/tlds directory. To use the library, you will need a taglib directive such as the following:

<%@ taglib uri="/WEB-INF/utiltaglib.tld" prefix="util" %>


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

This section documents the following 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

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

Example

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

Utility displayNumber Tag

This displays the specified number, 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

Example

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

Miscellaneous Utility Tags

This section documents the following tags:

Utility iterate Tag

Use this tag to iterate through a collection. Obtain the collection in the start tag; iterate through it 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

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 Sun Microsystems Java Servlet Specification, Version 2.2 (and higher). 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

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

Example

<util:lastModified />


Go to previous page Go to next page
Oracle
Copyright © 2002 Oracle Corporation.

All Rights Reserved.
Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index