Oracle9iAS Containers for J2EE JSP Tag Libraries and Utilities Reference Release 2 (9.0.2) Part Number A95883-01 |
|
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.
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:
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:
PAGE_SCOPE
, REQUEST_SCOPE
, SESSION_SCOPE
, or APPLICATION_SCOPE
)
page
, request
, session
, or application
)
JspScopeListener
)
application
object
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.
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:
The JspScopeListener
implementation requires the following:
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
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 |
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>
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");
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) {...} }
This section provides two examples of JspScopeListener
usage--first a JSP page and accompanying JavaBean, and then a servlet.
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.
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>
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); } }
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 } } }
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
Be aware of the following points, which apply to use of either the mail JavaBean (SendMailBean
) or the mail tag (sendMail
):
mail.jar
, containing the JavaMail packages, and jaf.jar
, for the JavaBeans Activation Framework, must be in your classpath for mail functionality. These files are provided with OC4J.
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".)
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:
Use the setSender()
method to specify the sender.
Use the setRecipient()
method to specify the primary recipient(s).
javax.mail.Session
), either directly or indirectly
There are three ways to supply a JavaMail session:
setHost()
method to specify a host system. In this case, a JavaMail session object will be created automatically.
setMailSession()
method to provide a JavaMail session object directly.
setSession()
method to specify the name of a JavaMail session object that already exists and is accessible through a "session string, javax.mail.Session
object" pair in the JSP page context. In this case, you must supply the page context instance as an input parameter when you call the sendMessage()
method to send the e-mail message.
All other SendMailBean
attributes are optional.
This section lists and describes SendMailBean
methods to send mail messages, close mail sessions, and set or get bean attributes.
Here are the public SendMailBean
methods:
void sendMessage()
void sendMessage(javax.servlet.jsp.PageContext)
Use the sendMessage()
method to send the e-mail message.
If you use the setSession()
method to supply a JavaMail session, then you must use the sendMessage(PageContext)
signature and provide the page context instance that holds the specified mail session instance.
If you use the setMailSession()
or setHost()
method to supply a JavaMail session, then you do not have to provide a page context in using the sendMessage()
method.
Also be aware, however, that specifying a page context instance may be relevant in determining the character set of an e-mail message with a "text" content type. If you provide no page context when invoking the sendMessage()
method, then the default character set is ISO-8859-1
. If you do provide a page context, then the default character set is that of the response
object of the page context. Also note that you can specify the content type and character set directly through the setContentType()
method.
void close()
Use this method if you want to release the resources of the JavaMail session instance from the SendMailBean
instance. This method does not actually close the session.
void setBcc(String s)
Specify a space-separated or comma-separated list of any IDs (e-mail addresses or aliases) to receive "blind" copies of the message. These IDs will be suppressed from the message "cc" field.
String getBcc()
void setCc(String s)
Specify a space-separated or comma-separated list of any IDs (e-mail addresses or aliases) to receive copies of the message. These IDs will appear in the message "cc" field.
String getCc()
void setContent(String s)
Specify the contents of the e-mail message.
String getContent()
void setContentEncoding(String s)
Specify the content encoding of the e-mail message. Specify "base64" or "B" for base64 encoding, "quoted-printable" or "Q" for quoted-printable encoding, "7bit" for seven-bit encoding, or "8bit" for eight-bit encoding. These content encodings are part of the JavaMail and RFC 2047 standards. Entries are case-insensitive.
The default content encoding setting is null
, in which case the encoding of the message and headers will be determined by the content. If most characters to be encoded are in ASCII, then quoted-printable encoding will be used; otherwise, base64
encoding will be used.
String getContentEncoding()
void setContentType(String s)
Specify the MIME type and optionally the character set of the message, such as in the following examples:
setContentType("text/html"); setContentType("text/html; charset=US-ASCII");
The default MIME type is "text/plain", but you cannot specify a character set without explicitly specifying that or some other text/xxxx
MIME type.
The default character set depends on whether you provide a JSP page context instance when you call the sendMessage()
method to send the e-mail message. If you provide no page context, then the default character set is ISO-8859-1
. If you do provide a page context, then the default character set is that of the response
object of the page context.
String getContentType()
void setHost(String s)
One of the ways to supply a JavaMail session is to specify a mail server host name, in which case SendMailBean
will obtain a session automatically. Use the setHost()
method for this purpose, providing a mail host name such as "gmail.oraclecorp.com".
See "SendMailBean Requirements" for an overview of supplying the JavaMail session.
String getHost()
void setMailSession(javax.mail.Session sessobj)
One of the ways to supply a JavaMail session is to provide the session object directly. Use the setMailSession()
method for this purpose, providing a javax.mail.Session
instance.
See "SendMailBean Requirements" for an overview of supplying the JavaMail session.
javax.mail.Session getMailSession()
This returns a JavaMail session that you had previously set.
void setRecipient(String s)
Specify a space-separated or comma-separated list of IDs (e-mail addresses or aliases) of the primary recipients of the message. These IDs will appear in the "to" field of the message. You must specify at least one recipient.
String getRecipient()
void setSender(String s)
Specify the ID (e-mail address or alias) of the message sender. This ID will appear in the "from" field of the message. You must specify the sender.
String getSender()
void setSession(String s)
One of the ways to supply a JavaMail session is to provide the name of a javax.mail.Session
instance that already exists in the JSP page context object. Use the setSession()
method for this purpose, specifying the name of the session instance.
In this case, when you use the sendMessage()
method to send the e-mail message, you must provide the javax.servlet.jsp.PageContext
instance as input.
See "SendMailBean Requirements" for an overview of supplying the JavaMail session.
String getSession()
void setSubject(String s)
Specify the subject line of the message.
String getSubject()
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 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 sendMail
tag supplies the following attributes:
host
(required if session
is not specified)--This is the appropriate mail host name, such as "gmail.oraclecorp.com". This is used in creating a JavaMail session object for the mail message. Alternatively, you can determine a JavaMail session through the session
attribute.
session
(required if host
is not specified)--This is the name of an existing JavaMail session object that can be retrieved from the JSP page context. Alternatively, you can determine a JavaMail session through the host
attribute.
sender
(required)--This is the ID (e-mail address or alias) of the sender of the message. This ID will appear in the "from" field of the message.
recipient
(required)--This is a space-separated or comma-separated list of IDs of the primary recipients of the message. These IDs will appear in the "to" field of the message.
cc
-- This is a space-separated or comma-separated list of IDs to receive a copy of the message. These IDs will appear in the "cc" field of the message.
bcc
--This is a space-separated or comma-separated list of IDs to receive a "blind" copy of the message. These IDs will be suppressed from the "cc" field.
subject
--This is the subject line of the message.
contentType
--This is for the MIME type of the message, and optionally a character set as well, such as in the following examples:
contentType="text/html" contentType="text/html; charset=US-ASCII"
The default MIME type is "text/plain", but you cannot specify a character set without explicitly specifying that or some other text/xxxx
MIME type.
The default character set is that of the response
object of the JSP page context.
contentEncoding
--Specify "B" or "base64" for base64 encoding, "Q" or "quoted-printable" for quoted-printable encoding, "7bit" for seven-bit encoding, or "8bit" for eight-bit encoding. These are standard JavaMail and RFC 2047 encodings. Entries are case-insensitive.
The default content encoding setting is null
, in which case the encoding of the message and headers will be determined by the content--if most characters to be encoded are in ASCII, then quoted-printable encoding will be used; otherwise, base64
encoding will be used.
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:
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
:
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:
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.
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.
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.
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:
Notes:
ConnBean
instance, the connection will be closed automatically at the end of the scope designated in the jsp:useBean
tag that invokes it. There is no such functionality for a Connection
instance.
ConnBean
uses and requires the JspScopeListener
interface. See "JSP Event-Handling--JspScopeListener" for information about that utility.
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.
Use the HttpDownloadBean
JavaBean or the httpDownload
tag as follows:
Note the following:
Once presented with a list of available files, the user can download them one at a time from the list.
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".)
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:
source
string (perhaps specified through user input) would be available for downloading, with the names of all these files presumably being displayed. A source of "*" matches all prefixes.
If this is of concern, you can consider protective measures such as the following:
source
values of "*" when downloading from file systems
source
value with a partial directory path or prefix string, such as a user name, to restrict the areas to which users have access
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.
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.
The following list summarizes required attributes for HttpUploadBean
:
destination
destinationType
, connection
fileaccess
table: table
, prefixColumn
, fileNameColumn
, dataColumn
fileType
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.
Here are descriptions of the public methods of HttpUploadBean
.
void upload(javax.servlet.http.HttpServletRequest req)
throws FileAccessException
Once all required and appropriate bean attributes have been set, use this method for the upload. The req
parameter is the servlet request instance containing the multipart form-encoded files. For a JSP page, use the implicit request
object.
void setBaseDir(javax.servlet.ServletContext sc
javax.servlet.http.HttpServletRequest req)
throws FileAccessException
For an upload to a file system, use this method to determine what to use as a base directory. It gets this information from the fileaccess.properties
file in your application /WEB-INF
directory, which it finds through the servlet context input parameter. The baseDir
setting, together with the destination
setting, specifies the absolute path to the upload directory.
The req
parameter is the servlet request instance to use in requesting the base directory information. For JSP pages, use the implicit request
object.
This method is not relevant for database uploads.
void setDestination(String destination)
This method is always required.
For an upload to a file system, destination
, together with the base directory, specifies the absolute path to the upload directory.
For an upload to a database, destination
is used as the file prefix (there is no "base directory"). The prefix is equivalent to a file system path and can be used to group files into a hierarchy. It is permissible to include separator characters such as "." and "/" in the destination string.
void setDestinationType(String destinationType)
throws FileAccessException
void setDestinationType(int destinationType)
throws FileAccessException
Use the overloaded setDestinationType()
method to specify whether the upload is to a file system or a database.
To upload to a database, set destinationType
to one of the following: the string "database", the defined String
constant FileAccessUtil.DATABASE
, the int
value 1, or the defined int
constant FileAccessUtil.LOCATION_TYPE_DATABASE
.
Uploading to a file system is the default, but if you want to specify this explicitly, set destinationType
to one of the following: the string "filesystem", the defined String
constant FileAccessUtil.FILESYSTEM
, the int
value 0, or the defined int
constant FileAccessUtil.LOCATION_TYPE_FILESYSTEM
.
FileAccessUtil
is in the oracle.jsp.webutil.fileaccess
package.
String getDestinationType()
Note there is a getter method for the string version only.
void setOverwrite(String overwrite)
throws FileAccessException
void setOverwrite(boolean overwrite)
Use the overloaded setOverwrite()
method to overwrite existing files or update rows with the same file name and prefix. This is relevant for both file system and database uploads.
Overwriting is enabled by default, but you can enable it explicitly with an overwrite
setting of the string "true" or the boolean value true
. Disable overwriting with a setting of the string "false" or the boolean value false
. String settings are case-insensitive. No settings are accepted other than those listed here.
void setFileType(String fileType)
throws FileAccessException
void setFileType(int fileType) throws FileAccessException
For an upload to a database, use the overloaded setFileType()
method to specify whether the data is to be stored in a BLOB for binary data (the default) or a CLOB for character data. For a CLOB, set fileType
to one of the following: the string "character", the defined String
constant FileAccessUtil.CHARACTER_FILE
, or the int
value 1. To explicitly specify a BLOB, set fileType
to one of the following: the string "binary", the defined String
constant FileAccessUtil.BINARY_FILE
, or the int value 0. String settings are case-insensitive. No settings are accepted other than those listed here.
FileAccessUtil
is in the oracle.jsp.webutil.fileaccess
package.
String getFileType()
Note there is a getter method for the string version only.
void setTable(String tableName)
For an upload to a database table other than the default fileaccess
table, use this method to specify the table name.
String getTable()
void setPrefixColumn(String prefixColumnName)
For an upload to a database table other than the default fileaccess
table, use this method to specify the name of the column containing the file prefix. (In fileaccess
, this column name is fileprefix
.) The destination
value will be written into this column.
String getPrefixColumn()
void setFileNameColumn(String fileNameColumnName)
For an upload to a database table other than the default fileaccess
table, use this method to specify the name of the column containing the file name. (In fileaccess
, this column name is filename
.) File names will include any file name extensions.
String getFileNameColumn()
void setDataColumn(String dataColumnName)
For an upload to a database table other than the default fileaccess
table, use this method to specify the name of the BLOB or CLOB column containing the file contents. (In fileaccess
, this column name is data
.)
String getDataColumn()
void setConnection(ConnBean conn)
void setConnection(java.sql.Connection conn)
For an upload to a database table (default table or otherwise), use this method to provide a database connection. You can provide an instance of either oracle.jsp.dbutil.ConnBean
or the standard java.sql.Connection
type. For information about the ConnBean
JavaBean, see "ConnBean for a Database Connection".
If you use a Connection
instance, you must explicitly open and close it. For a ConnBean
instance, this is handled automatically.
java.util.Enumeration getFileNames()
This method returns an Enumeration
instance containing the names of the files that were uploaded. (This functionality is not available through the httpUpload
tag.)
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 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".
HttpDownloadBean
, as with HttpUploadBean
, extends HttpFileAccessBean
, which itself is not intended for public use.
See "Overview of File Uploading" for related information.
The following list summarizes required attributes for HttpDownloadBean
:
source
sourceType
, connection
fileaccess
table: table
, prefixColumn
, fileNameColumn
, dataColumn
fileType
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.
Here are descriptions of the public methods of HttpDownloadBean
.
void listFiles(javax.servlet.http.HttpServletRequest req)
throws FileAccessException
Once all required and appropriate bean attributes have been set, use this method to list the files available for download. These are files in the source directory or matching the source database prefix. The req
parameter is the servlet response instance. For a JSP page, use the implicit request
object.
For use from the file list, you can create HREF
links to DownloadServlet
, passing it each file and file prefix, allowing users to click on the link for each file they want to download.
java.util.Enumeration getFileNames()
This method returns an Enumeration
instance containing the names of the files that are available for download. It requires that the listFiles()
method was already called--listFiles()
writes the file names to memory and to the JSP page or servlet; getFileNames()
reads them from memory.
void setBaseDir(javax.servlet.ServletContext sc
javax.servlet.http.HttpServletRequest req)
throws FileAccessException
For a download from a file system, use this method to determine what to use as the base directory. It gets this information from the fileaccess.properties
file in your application /WEB-INF
directory, which it finds through the servlet context input parameter. The baseDir
setting, together with the source
setting, specifies the absolute path to the directory from which files will be downloaded.
The sc
parameter is the servlet context instance for the application. For JSP pages, use the implicit application
object.
The req
parameter is for the servlet request instance to use in requesting the base directory information. For JSP pages, use the implicit request
object.
A base directory is not relevant for downloads from a database.
void setSource(String source)
This is always required.
For a download from a file system, source
, together with the base directory, specifies the absolute path to the directory from which files will be downloaded. If source
is set to "*", then all directories under the base directory will be available for downloading.
For a download from a database, source
is used as the file prefix (base directory is not relevant). The prefix is equivalent to a file system path and can be used to group files into a hierarchy. If recurse
is enabled, "%" will be appended onto the source
value, and the WHERE
clause for the query will contain an appropriate LIKE
clause. Therefore, all files with prefixes that are partially matched by the source
value will be available for download. If you want to match all rows in the database table, set source
to "*".
void setSourceType(String sourceType)
throws FileAccessException
void setSourceType(int sourceType)
throws FileAccessException
Use the overloaded setSourceType()
method to specify whether the download is from a file system or a database.
To download from a database, set sourceType
to one of the following: the string "database", the defined String
constant FileAccessUtil.DATABASE
, the int
value 1, or the defined int
constant FileAccessUtil.LOCATION_TYPE_DATABASE
.
Downloading from a file system is the default, but if you want to specify this explicitly, set sourceType
to one of the following: the string "filesystem", the defined String
constant FileAccessUtil.FILESYSTEM
, the int
value 0, or the defined int
constant FileAccessUtil.LOCATION_TYPE_FILESYSTEM
.
FileAccessUtil
is in the oracle.jsp.webutil.fileaccess
package.
String getSourceType()
Note there is a getter method for the string version only.
void setRecurse(String recurse) throws FileAccessException
void setRecurse(boolean recurse)
Use the overloaded setRecurse()
method to enable or disable recursive downloading, where files in file system subdirectories or with additional database prefix information will also be available for downloading. As an example of recursive downloading from a database, assume source
is set to "/user". Recursive downloading would also find matches for files with prefixes such as /user/bill
and /user/mary
, and also such as /user1
, /user2
, /user1/tom
, and /user2/susan
.
Recursive downloading is enabled by default, but you can enable it explicitly with a recurse
setting of the string "true" or the boolean true
. Disable recursive downloading with a setting of the string "false" or the boolean false
. String settings are case-insensitive. No settings are accepted other than those listed here.
void setFileType(String fileType)
throws FileAccessException
void setFileType(int fileType) throws FileAccessException
For a download from a database, use the overloaded setFileType()
method to specify whether the data is stored in a BLOB for binary data (the default) or a CLOB for character data. For a CLOB, set fileType
to one of the following: the string "character", the defined String
constant FileAccessUtil.CHARACTER_FILE
, or the int
value 1. To explicitly specify a BLOB, set fileType
to one of the following: the string "binary", the defined String
constant FileAccessUtil.BINARY_FILE
, or the int
value 0. String settings are case-insensitive. No settings are accepted other than those listed here.
FileAccessUtil
is in the oracle.jsp.webutil.fileaccess
package.
String getFileType()
Note there is a getter method for the string version only.
void setTable(String tableName)
For a download from a database table other than the default fileaccess
table, use this method to specify the table name.
String getTable()
void setPrefixColumn(String prefixColumnName)
For a download from a database table other than the default fileaccess
table, use this method to specify the name of the column containing the file prefix. (In fileaccess
, this column name is fileprefix
.)
String getPrefixColumn()
void setFileNameColumn(String fileNameColumnName)
For a download from a database table other than the default fileaccess
table, use this method to specify the name of the column containing the file name. (In fileaccess
, this column name is filename
.) The file name includes any file name extension.
String getFileNameColumn()
void setDataColumn(String dataColumnName)
For a download from a database table other than the default fileaccess
table, use this method to specify the name of the BLOB or CLOB column that holds the file contents. (In fileaccess
, this column name is data
.)
String getDataColumn()
void setConnection(ConnBean conn)
void setConnection(java.sql.Connection conn)
For a download from a database table (default table or otherwise), use this method to provide a database connection. You can provide an instance of either oracle.jsp.dbutil.ConnBean
or the standard java.sql.Connection
type. For information about the ConnBean
JavaBean, see "ConnBean for a Database Connection".
If you use a Connection
instance, you must explicitly open and close it. For a ConnBean
instance, this is handled automatically.
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>
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
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.
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:
|
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.
<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" ] />
formsAction
(required)--This is to indicate the action that will be performed after the form is submitted. For example, formsAction
could be the name of a JSP page that uses HttpUploadBean
or the httpUpload
tag.
maxFiles
--Use this if you want to specify the number of input lines you want to appear in the form. The default is 1.
fileNameSize
--Use this if you want to specify the character-width of the file name input box(es). The default is 20 characters.
maxFileNameSize
--Use this if you want to specify the maximum number of characters allowed in a file name. The default is 80 characters.
includeNumbers
--Set this to "true" if you want the file name input boxes to be numbered. The default setting is "false".
submitButtonText
--Use this if you want to specify the text that appears on the "submit" button of the form. The default is "Send".
This tag wraps the functionality of the HttpUploadBean
JavaBean, paralleling its attributes. See "Overview of File Uploading" and "The HttpUploadBean" for related information.
<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" ] />
destination
(required)--For uploading to a file system, this indicates the path, beneath the base directory supplied in the /WEB-INF/fileaccess.properties
file, of the directory into which files will be uploaded. For uploading to a database, destination
indicates the file prefix, conceptually equivalent to a file system path.
destinationType
--Set this to "database" for uploading to a database. The default is to upload to a file system, but you can also explicitly set it to "filesystem". These values are case-insensitive.
connId
--For uploading to a database, use this attribute to provide a ConnBean
connection ID for the database connection to be used. Or, alternatively, use the httpUpload
tag inside a dbOpen
tag to implicitly use the dbOpen
connection. For information about the ConnBean
JavaBean and dbOpen
tag provided with OC4J, see Chapter 4, "Data-Access JavaBeans and Tags".
scope
--For uploading to a database, use this attribute to specify the scope of the ConnBean
instance for the connection. The scope setting here must match the scope setting when the ConnBean
instance was created, such as in a dbOpen
tag. If the httpUpload
tag is nested inside a dbOpen
tag, then there is no need to specify connId
or scope
--that information will be taken from the dbOpen
tag. Otherwise, the default scope is page
.
overwrite
--Set this to "false" if you do not want to overwrite existing files that have the same paths and names as the files you are uploading, or if you do not want to update rows with the same file name and prefix for database uploading. In this case, an error will be generated if a file already exists. By default, overwrite
is set to "true" and httpUpload
overwrites files.
fileType
--For uploading to a database, set this attribute to "character" for character data, which will be written into a CLOB. The default setting is "binary" for binary data, which will be written into a BLOB.
table
--For uploading to a database table other than the default fileaccess
table, use this attribute to specify the table name.
prefixColumn
--For uploading to a database table other than the default fileaccess
table, use this attribute to specify the name of the column containing file prefixes. This column is where the destination
values will be written.
fileNameColumn
--For uploading to a database table other than the default fileaccess
table, use this attribute to specify the name of the column containing file names.
dataColumn
--For uploading to a database table other than the default fileaccess
table, use this attribute to specify the name of the column containing file contents.
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>
This tag wraps the functionality of the HttpDownloadBean
JavaBean, paralleling its attributes. See "Overview of File Downloading" and "The HttpDownloadBean" for related information.
<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" ] />
servletPath
(required)--The path to the Oracle DownloadServlet
, which executes the actual download of each file. For example, if DownloadServlet
has been installed in the application app
and mapped to the name download
, then use "/app/download/", with leading and trailing slashes, as the servletPath
setting. The httpDownload
tag handler uses this path in constructing the URL to DownloadServlet
.
See "The Download Servlet" for more information about this servlet.
source
(required)--For downloading from a file system, this attribute indicates the path, beneath the base directory supplied in the file /WEB-INF/fileaccess.properties
, of the directory from which files are retrieved. A value of "*" results in all directories under the base directory being available.
For downloading from a database, this attribute indicates the file prefix, conceptually equivalent to a file system path. If recurse
is enabled, "%" will be appended onto the source
value, and the WHERE
clause for the query will contain an appropriate LIKE
clause. Therefore, all files with prefixes that are partially matched by the source value will be available for download. If you want to match all rows in the database table, set source
to "*".
sourceType
--Set this to "database" for downloading from a database. The default is to download from a file system, or you can explicitly set this to "filesystem".
connId
--For downloading from a database, use this attribute to provide a ConnBean
connection ID for the database connection to be used. Or, alternatively, you can use the httpDownload
tag inside a dbOpen
tag to implicitly use the dbOpen
connection. For information about the ConnBean
JavaBean and dbOpen
tag provided with OC4J, see Chapter 4, "Data-Access JavaBeans and Tags".
scope
--For downloading from a database, use this attribute to specify the scope of the ConnBean
instance for the connection. The scope setting here must match the scope setting when the ConnBean
instance was created, such as in a dbOpen
tag. If the httpDownload
tag is nested inside a dbOpen
tag, then there is no need to specify connId
or scope
--that information will be taken from the dbOpen
tag. Otherwise, the default scope is page
.
recurse
--Set this to "false" if you do not want recursive downloading, where files in file system subdirectories or with additional database prefix information will also be available for download. As an example of recursive downloading from a database, assume you have set source
to "/user". Recursive downloading would also find matches for files with prefixes such as /user/bill
and /user/mary
, and also such as /user1
, /user2
, /user1/tom
, and /user2/susan
. The default is recursive downloading, or you can enable it explicitly with a setting of "true".
fileType
--For downloading from a database, set this attribute to "character" for character data, which will be retrieved from a CLOB. The default setting is "binary" for binary data, which will be retrieved from a BLOB.
table
--For downloading from a database table other than the default fileaccess
table, use this attribute to specify the table name.
prefixColumn
--For downloading from a database table other than the default fileaccess
table, use this attribute to specify the name of the column containing file prefixes, which is where source
values are stored.
fileNameColumn
--For downloading from a database table other than the default fileaccess
table, use this attribute to specify the name of the column containing file names. File names include any file name extensions.
dataColumn
--For downloading from a database table other than the default fileaccess
table, use this attribute to specify the name of the column that stores the file contents.
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>
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:
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:
<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.
<ejb-ref-type>
subelement specifies the category of EJB.
<home>
subelement specifies the package and type of the EJB home interface.
<remote>
subelement specifies the package and type of the EJB remote interface.
These values are reflected in attribute values of the EJB tags.
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 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:
useBean
tag, and either the useBean
tag value
attribute or a nested createBean
tag
iterate
tag
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.
The useHome
tag looks up the home interface for the EJB and creates an instance of it.
<ejb:useHome id = "home_instance_name" type = "home_interface_type" location = "home_lookup_name" />
This tag uses no body.
id
(required)--Specify a name for the home interface instance. 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.
<ejb:useHome id="aomHome" type="com.acme.atm.ejb.AccountOwnerManagerHome" location="java:comp/env/ejb/accountOwnerManager" />
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. |
<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>
id
(required)--Specify an instance name for the EJB.
type
(required)--This is 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 is page
scope.
This example shows the use of an EJB that has already been instantiated.
<ejb:useBean id="bean" type="com.acme.MyBean" scope="session" />
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.
<ejb:createBean instance = "<%=Object%>" />
This tag uses no body.
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>
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:
|
<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.
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.
<ejb:iterate id="account" type="com.acme.atm.ejb.Account" collection="<%=accountManager.getOwnerAccounts()%>" max="100"> <jsp:getProperty name="account" property="id" /> </ejb:iterate>
This section provides examples of EJB tag usage, one using a session bean and one use an entity bean.
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:
home
instance of the EJB home interface. Note that the type
value of the useHome
tag matches the <home>
value of the <ejb-ref>
element in the web.xml
file, and that the location
value of useHome
reflects the <ejb-ref-name>
value of the <ejb-ref>
element.
home.create()
method to create the demo
instance of the EJB. Note that the type
value of the useBean
tag matches the <remote>
value of the <ejb-ref>
element in the web.xml
file.
demo.getName()
method to print a user name.
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:
home
instance of the EJB home interface. Note that the type
value of the useHome
tag matches the <home>
value of the <ejb-ref>
element in the web.xml
file, and that the location
value of useHome
reflects the <ejb-ref-name>
value of the <ejb-ref>
element.
home.findAll()
method to return a collection of EJBs. Note that the type
value in the iterate
tag matches the <remote>
value of the <ejb-ref>
element in the web.xml
file.
demo
for the current instance, and using the demo.getName()
and demo.getId()
methods to output information from each EJB.
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:
|
This section documents the following tags:
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.
<util:displayCurrency amount = "<%=Double%>" [ locale = "<%=Locale%>" ] />
This tag uses no body.
amount
(required)--Specify the amount to format.
locale
--Optionally specify a locale (a java.util.Locale
instance).
<util:displayCurrency amount="<%=account.getBalance()%>" locale="<%=account.getLocale()%>" />
This tag displays a specified date, formatted appropriately for the locale. If no locale is specified, the system default locale is used.
<util:displayDate date = "<%=Date%>" [ locale = "<%=Locale%>" ] />
This tag uses no body.
date
(required)--Specify the date to format (a java.util.Date
instance).
locale
--Optionally specify a locale (a java.util.Locale
instance).
<util:displayDate date="<%=account.getDate()%>" locale="<%=account.getLocale()%>" />
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.
<util:displayNumber number = "<%=Double%>" [ locale = "<%=Locale%>" ] [ format = "<%=Format%>" ] />
This tag uses no body.
number
(required)--Specify the number to format.
locale
--Optionally specify the locale (a java.util.Locale
instance).
format
--Optionally specify a format (a java.text.Format
instance).
<util:displayNumber number="<%=shoe.getSize()%>" />
This section documents the following tags:
Use this tag to iterate through a collection. Obtain the collection in the start tag; iterate through it in the body.
<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.
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 for the collection itself.
max
--Optionally specify a maximum number of elements to iterate through.
<util:iterate id="contact" type="com.acme.connections.Contact" collection="<%=company.getContacts()%>" > <jsp:getProperty name="contact" property="name"/> </util:iterate>
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.
<util:ifInRole role = "<%=String%>" [ include = "true" | "false" ] > ... body to include ... </util:ifInRole>
role
(required)--Check to see if the user is in this specified 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.
<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>
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.
<util:lastModified [ locale = "<%=Locale%>" ] />
This tag uses no body.
<util:lastModified />
|
Copyright © 2002 Oracle Corporation. All Rights Reserved. |
|