OracleJSP Support for JavaServer Pages Developer's Guide and Reference Release 1.1.2.3 Part Number A90208-01 |
|
This chapter discusses extended functionality offered by OracleJSP, covering the following topics:
Portable extensions are provided through Oracle's JSP Markup Language (JML) custom tags, JML extended datatypes, SQL custom tags, and data-access JavaBeans. You can use these features in other JSP environments.
Non-portable extensions are those that require OracleJSP for translation and execution.
Extended application and session support for servlet 2.0 environments is supplied through Oracle globals.jsa
functionality and also requires OracleJSP.
The Oracle extensions documented in this section are implemented either through the Oracle JSP Markup Language (JML) sample tag library, custom JavaBeans, or the custom SQL tag library. These extensions are portable to any standard JSP environment. This includes the following:
To use any of the JML functionality, see "Overview of the JSP Markup Language (JML) Sample Tag Library".
Important:
To work around shortcomings for JSP usage in the Java primitive datatypes and java.lang
wrapper types (as discussed in "OracleJSP Extended Datatypes"), OracleJSP provides the following JavaBean classes in the oracle.jsp.jml
package to act as wrappers for the most common Java datatypes:
JmlBoolean
to represent a boolean
value
JmlNumber
to represent an int
value
JmlFPNumber
to represent a double
value
JmlString
to represent a String
value
Each of these classes has a single attribute, value
, and includes methods to get the value, set the value from input in various formats, test whether the value is equal to a value specified in any of several formats, and convert the value to a string.
Alternatively, instead of using the getValue()
and setValue()
methods, you can use the jsp:getProperty
and jsp:setProperty
tags, as with any other bean.
The following example creates a JmlNumber
instance called count
that has application
scope:
<jsp:useBean id="count" class="oracle.jsp.jml.JmlNumber" scope="application" />
Later, assuming that the value has been set elsewhere, you can access it as follows:
<h3> The current count is <%=count.getValue() %> </h3>
The following example creates a JmlNumber
instance called maxSize
that has request
scope, and sets it using setProperty
:
<jsp:useBean id="maxSize" class="oracle.jsp.jml.Number" scope="request" > <jsp:setProperty name="maxSize" property="value" value="<%= 25 %>" /> </jsp:useBean>
The remainder of this section documents the public methods of the four extended datatype classes, followed by an example.
A JmlBoolean
object represents a Java boolean
value.
The getValue()
and setValue()
methods get or set the value
property of the bean as a Java boolean
value.
The setTypedValue()
method has several signatures and can set the value
property from a string (such as "true" or "false"), a java.lang.Boolean
value, a Java boolean
value, or a JmlBoolean
value. For the string input, conversion of the string is performed according to the same rules as for the standard java.lang.Boolean.valueOf()
method.
void setTypedValue(String)
void setTypedValue(Boolean)
void setTypedValue(boolean)
void setTypedValue(JmlBoolean)
The equals()
method tests whether the value
property is equal to the specified Java boolean
value.
The typedEquals()
method has several signatures and tests whether the value
property has a value equivalent to a specified string (such as "true" or "false"), java.lang.Boolean
value, or JmlBoolean
value.
The toString()
method returns the value
property as a java.lang.String
value, either "true" or "false".
A JmlNumber
object represents a 32-bit number equivalent to a Java int
value.
The getValue()
and setValue()
methods get or set the value
property of the bean as a Java int
value.
The setTypedValue()
method has several signatures and can set the value
property from a string, a java.lang.Integer
value, a Java int
value, or a JmlNumber
value. For the string input, conversion of the string is performed according to the same rules as for the standard java.lang.Integer.decode()
method.
void setTypedValue(String)
void setTypedValue(Integer)
void setTypedValue(int)
void setTypedValue(JmlNumber)
The equals()
method tests whether the value
property is equal to the specified Java int
value.
The typedEquals()
method has several signatures and tests whether the value
property has a value equivalent to a specified string (such as "1234"), java.lang.Number
value, or JmlNumber
value.
The toString()
method returns the value
property as an equivalent java.lang.String
value (such as "1234"). This method has the same functionality as the standard java.lang.Integer.toString()
method.
A JmlFPNumber
object represents a 64-bit floating point number equivalent to a Java double
value.
The getValue()
and setValue()
methods get or set the value
property of the bean as a Java double
value.
The setTypedValue()
method has several signatures and can set the value
property from a string (such as "3.57"), a java.lang.Integer
value, a Java int
value, a java.lang.Float
value, a Java float
value, a java.lang.Double
value, a Java double
value, or a JmlFPNumber
value. For the string input, conversion of the string is according to the same rules as for the standard java.lang.Double.valueOf()
method.
void setTypedValue(String)
void setTypedValue(Integer)
void setTypedValue(int)
void setTypedValue(Float)
void setTypedValue(float)
void setTypedValue(Double)
void setTypedValue(double)
void setTypedValue(JmlFPNumber)
The equals()
method tests whether the value
property is equal to the specified Java double
value.
The typedEquals()
method has several signatures and tests whether the value
property has a value equivalent to a specified string (such as "3.57"), java.lang.Integer
value, Java int
value, java.lang.Float
value, Java float
value, java.lang.Double
value, Java double
value, or JmlFPNumber
value.
boolean typedEquals(String)
boolean typedEquals(Integer)
boolean typedEquals(int)
boolean typedEquals(Float)
boolean typedEquals(float)
boolean typedEquals(Double)
boolean typedEquals(JmlFPNumber)
The toString()
method returns the value
property as a java.lang.String
value (such as "3.57"). This method has the same functionality as the standard java.lang.Double.toString()
method.
A JmlString
object represents a java.lang.String
value.
The getValue()
and setValue()
methods get or set the value
property of the bean as a java.lang.String
value. If the input in a setValue()
call is null, then the value
property is set to an empty (zero-length) string.
The toString()
method is functionally equivalent to the getValue()
method.
The setTypedValue()
method sets the value
property according to the specified JmlString
value. If the JmlString
value is null, then the value
property is set to an empty (zero-length) string.
The isEmpty()
method tests whether the value
property is an empty (zero-length) string: ""
The equals()
method has two signatures and tests whether the value
property is equal to a specified java.lang.String
value or JmlString
value.
This example illustrates use of JML datatype JavaBeans for management of simple datatypes at scope. The page declares four session objects--one for each JML type. The page presents a form that allows you to enter values for each of these types. Once new values are submitted, the form displays both the new values and the previously set values. In the process of generating this output, the page updates the session objects with the new form values.
<jsp:useBean id = "submitCount" class = "oracle.jsp.jml.JmlNumber" scope = "session" /> <jsp:useBean id = "bool" class = "oracle.jsp.jml.JmlBoolean" scope = "session" > <jsp:setProperty name = "bool" property = "value" param = "fBoolean" /> </jsp:useBean> <jsp:useBean id = "num" class = "oracle.jsp.jml.JmlNumber" scope = "session" > <jsp:setProperty name = "num" property = "value" param = "fNumber" /> </jsp:useBean> <jsp:useBean id = "fpnum" class = "oracle.jsp.jml.JmlFPNumber" scope = "session" > <jsp:setProperty name = "fpnum" property = "value" param = "fFPNumber" /> </jsp:useBean> <jsp:useBean id = "str" class = "oracle.jsp.jml.JmlString" scope = "session" > <jsp:setProperty name = "str" property = "value" param = "fString" /> </jsp:useBean> <HTML> <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=iso-8859-1"> <META NAME="GENERATOR" Content="Visual Page 1.1 for Windows"> <TITLE>OracleJSP Extended Datatypes Sample</TITLE> </HEAD> <BODY BACKGROUND="images/bg.gif" BGCOLOR="#FFFFFF"> <% if (submitCount.getValue() > 1) { %> <h3> Last submitted values </h3> <ul> <li> bool: <%= bool.getValue() %> <li> num: <%= num.getValue() %> <li> fpnum: <%= fpnum.getValue() %> <li> string: <%= str.getValue() %> </ul> <% } if (submitCount.getValue() > 0) { %> <jsp:setProperty name = "bool" property = "value" param = "fBoolean" /> <jsp:setProperty name = "num" property = "value" param = "fNumber" /> <jsp:setProperty name = "fpnum" property = "value" param = "fFPNumber" /> <jsp:setProperty name = "str" property = "value" param = "fString" /> <h3> New submitted values </h3> <ul> <li> bool: <jsp:getProperty name="bool" property="value" /> <li> num: <jsp:getProperty name="num" property="value" /> <li> fpnum: <jsp:getProperty name="fpnum" property="value" /> <li> string: <jsp:getProperty name="str" property="value" /> </ul> <% } %> <jsp:setProperty name = "submitCount" property = "value" value = "<%= submitCount.getValue() + 1 %>" /> <FORM ACTION="index.jsp" METHOD="POST" ENCTYPE="application/x-www-form-urlencoded"> <P> <pre> boolean test: <INPUT TYPE="text" NAME="fBoolean" VALUE="<%= bool.getValue() %>" > number test: <INPUT TYPE="text" NAME="fNumber" VALUE="<%= num.getValue() %>" > fpnumber test: <INPUT TYPE="text" NAME="fFPNumber" VALUE="<%= fpnum.getValue() %>" > string test: <INPUT TYPE="text" NAME="fString" VALUE= "<%= str.getValue() %>" > </pre> <P> <INPUT TYPE="submit"> </FORM> </BODY> </HTML>
JSP technology can be used to produce dynamic XML pages as well as dynamic HTML pages. OracleJSP supports the use of XML and XSL technology with JSP pages in two ways:
Additionally, the oracle.xml.sql.query.OracleXMLQuery
class is provided with Oracle9i as part of the XML-SQL utility for XML functionality in database queries. This class requires file xsu12.jar
(for JDK 1.2.x) or xsu111.jar
(for JDK 1.1.x), which is also required for XML functionality in the OracleJSP data-access JavaBeans, and which is provided with Oracle9i.
For a JSP sample using OracleXMLQuery
, see "XML Query--XMLQuery.jsp".
For information about the OracleXMLQuery
class and other XML-SQL utility features, refer to the Oracle9i Application Developer's Guide - XML and the Oracle9i XML Reference.
JSP tags, such as <%...%>
for scriptlets, <%!...%>
for declarations, and <%=...%>
for expressions, are not syntactically valid within an XML document. Sun Microsystems addressed this in the JavaServer Pages Specification, Version 1.1 by defining equivalent JSP tags using syntax that is XML-compatible. This is implemented through a standard DTD that you can specify within a jsp:root
start tag at the beginning of an XML document.
This functionality allows you, for example, to write XML-based JSP pages in an XML authoring tool.
OracleJSP does not use this DTD directly or require you to use a jsp:root
tag, but the OracleJSP translator includes logic to recognize the alternative syntax specified in the standard DTD. Table 5-1 documents this syntax.
JSP action tags, such as jsp:useBean
, for the most part already use syntax that complies with XML. Changes due to quoting conventions or for request-time attribute expressions may be necessary, however.
Many uses of XML and XSL for dynamic pages require an XSL transformation to occur in the server before results are returned to the client.
OracleJSP provides two synonymous JML tags to simplify this process. Use either the JML transform
tag or the JML styleSheet
tag (their effects are identical), as in the following example:
<jml:transform href="xslRef" > ...Tag body contains regular JSP commands and static text that produce the XML code that the stylesheet is to be applies to... </jml:transform >
(The jml:
prefix is used by convention, but you can specify any prefix in your taglib
directive.)
Important: If you will use any JML tags, refer to "Overview of the JSP Markup Language (JML) Sample Tag Library". |
Note the following regarding the href
parameter:
http://
host
[:
port
]/
path
), an application-relative JSP reference (starting with "/"), or a page-relative JSP reference (not starting with "/"). See "Indirectly Requesting a JSP Page" for information about application-relative and page-relative paths.
href
is a static Java string. However, you can use standard JSP expression syntax to provide a dynamically computed value.
Typically, you would use the transform
or styleSheet
tag to transform an entire page. However, the tag applies only to what is in its body, between its start and end tags. Therefore, you can have distinct XSL blocks within a page, each block bounded by its own transform
or styleSheet
tag set, specifying its own href
pointer to the appropriate stylesheet.
This section provides a sample XSL stylesheet and a sample JSP page that uses the jml:transform
tag to filter its output through the stylesheet. (This is a simplistic example--the XML in the page is static. A more realistic example might use the JSP page to dynamically generate all or part of the XML before performing the transformation.)
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="page"> <html> <head> <title> <xsl:value-of select="title"/> </title> </head> <body bgcolor="#ffffff"> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="title"> <h1 align="center"> <xsl:apply-templates/> </h1> </xsl:template> <xsl:template match="paragraph"> <p align="center"> <i> <xsl:apply-templates/> </i> </p> </xsl:template> </xsl:stylesheet>
<%@ page session = "false" %> <%@ taglib uri="/WEB-INF/jmltaglib.tld" prefix="jml" %> <jml:transform href="style/hello.xsl" > <page> <title>Hello</title> <content> <paragraph>This is my first XML/XSL file!</paragraph> </content> </page> </jml:transform>
This example results in the following output:
OracleJSP supplies a set of custom JavaBeans for accessing an Oracle database or middle-tier database cache (either is referred to simply as "the database" in the discussion below). The following beans are included in the oracle.jsp.dbutil
package:
ConnBean
opens a simple database connection.
ConnCacheBean
uses Oracle's connection caching implementation for database connections. (This requires JDBC 2.0.)
DBBean
executes a database query.
CursorBean
provides general DML support for queries; UPDATE
, INSERT
, and DELETE
statements; and stored procedure calls.
For examples using these beans, see "Data-Access JavaBean Samples".
All four beans implement the OracleJSP JspScopeListener
interface for event notification. See "OracleJSP Event Handling--JspScopeListener".
This section presumes a working knowledge of Oracle JDBC. Consult the Oracle9i JDBC Developer's Guide and Reference as necessary.
Use oracle.jsp.dbutil.ConnBean
to establish a simple database connection (one that uses no connection pooling or caching).
ConnBean
has the following properties:
user
(user ID for database schema)
password
(user password)
URL
(database connection string)
stmtCacheSize
(cache size for Oracle JDBC statement caching)
Setting stmtCacheSize
enables the Oracle JDBC statement caching feature. See "JDBC Statement Caching" for a brief overview of statement caching features and limitations.
executeBatch
(batch size for Oracle JDBC update batching)
Setting executeBatch
enables Oracle JDBC update batching. See "Update Batching" for a brief overview of this feature.
preFetch
(number of statements to prefetch in Oracle JDBC row prefetching)
Setting preFetch
enables Oracle JDBC row prefetching. Refer to "Row Prefetching" for a brief overview of this feature.
ConnBean
provides the following setter and getter methods for these properties:
void setUser(String)
String getUser()
void setPassword(String)
String getPassword()
void setURL(String)
String getURL()
void setStmtCacheSize(int)
int getStmtCacheSize()
void setExecuteBatch(int)
int getExecuteBatch()
void setPreFetch(int)
int getPreFetch()
Use the following methods to open and close a connection:
void connect()
--Establish a database connection using ConnBean
property settings.
void close()
--Close the connection and any open cursors.
Use the following method to open a cursor and return a CursorBean
object:
or:
CursorBean getCursorBean(int)
Input the following:
int
constants to specify the type of JDBC statement you want: CursorBean.PLAIN_STMT
(for a Statement
object), CursorBean.PREP_STMT
(for a PreparedStatement
object), or CursorBean.CALL_STMT
(for a CallableStatement
object)
CursorBean
method call that executes the statement)
See "CursorBean for DML and Stored Procedures" for information about CursorBean
functionality.
Use oracle.jsp.dbutil.ConnCacheBean
to use the Oracle JDBC connection caching mechanism (using JDBC 2.0 connection pooling) for your database connections. For a brief overview of connection caching, see "Database Connection Caching".
ConnCacheBean
has the following properties:
user
(user ID for database schema)
password
(user password)
URL
(database connection string)
maxLimit
(maximum number of connections allowed by this cache)
minLimit
(minimum number of connections existing for this cache)
If you are using fewer than this number, then there will also be connections in the "idle pool" of the cache.
stmtCacheSize
(cache size for Oracle JDBC statement caching)
Setting stmtCacheSize
enables the Oracle JDBC statement caching feature. See "JDBC Statement Caching" for a brief overview of Oracle JDBC statement caching features and limitations.
cacheScheme
(type of cache, indicated by one of the following int
constants):
DYNAMIC_SCHEME
--New pooled connections can be created above and beyond the maximum limit, but each one is automatically closed and freed as soon as the logical connection instance that it provided is no longer in use.
FIXED_WAIT_SCHEME
--When the maximum limit is reached, any new connection waits for an existing connection object to be released.
FIXED_RETURN_NULL_SCHEME
--When the maximum limit is reached, any new connection fails (null
is returned) until connection objects have been released.
The ConnCacheBean
class supports methods defined in the Oracle JDBC OracleConnectionCacheImpl
class, including the following getter and setter methods for its properties:
void setUser(String)
String getUser()
void setPassword(String)
String getPassword()
void setURL(String)
String getURL()
void setMaxLimit(int)
int getMaxLimit()
void setMinLimit(int)
int getMinLimit()
void setStmtCacheSize(int)
int getStmtCacheSize()
void setCacheScheme(int)
Specify ConnCacheBean.DYNAMIC_SCHEME
, ConnCacheBean.FIXED_WAIT_SCHEME
, or ConnCacheBean.FIXED_RETURN_NULL_SCHEME
.
int getCacheScheme()
Returns ConnCacheBean.DYNAMIC_SCHEME
, ConnCacheBean.FIXED_WAIT_SCHEME
, or ConnCacheBean.FIXED_RETURN_NULL_SCHEME
.
The ConnCacheBean
class also inherits properties and related getter and setter methods from the oracle.jdbc.pool.OracleDataSource
class. This provides getter and setter methods for the following properties: databaseName
, dataSourceName
, description
, networkProtocol
, portNumber
, serverName
, and driverType
. For information about these properties and their getter and setter methods, see the Oracle9i JDBC Developer's Guide and Reference.
Use the following methods to open and close a connection:
Connection getConnection()
--Get a connection from the connection cache using ConnCacheBean
property settings.
void close()
--Close all connections and any open cursors.
Although the ConnCacheBean
class does not support Oracle JDBC update batching and row prefetching directly, you can enable these features by calling the setDefaultExecuteBatch(int)
and setDefaultRowPrefetch(int)
methods of the Connection
object that you retrieve from the getConnection()
method. Alternatively, you can use the setExecuteBatch(int)
and setRowPrefetch(int)
methods of JDBC statement objects that you create from the Connection
object (update batching is supported only in prepared statements). See "Update Batching" and "Row Prefetching" for brief overviews of these features.
Notes:
|
Use oracle.jsp.dbutil.DBBean
to execute queries only.
DBBean
has the following properties:
DBBean
provides the following setter and getter methods for these properties:
void setUser(String)
String getUser()
void setPassword(String)
String getPassword()
void setURL(String)
String getURL()
Use the following methods to open and close a connection:
void connect()
--Establish a database connection using DBBean
property settings.
void close()
--Close the connection and any open cursors.
Use either of the following methods to execute a query:
String getResultAsHTMLTable(String)
--Input a string that contains the SELECT
statement.
This method returns a string with the HTML commands necessary to output the result set as an HTML table. SQL column names (or aliases) are used for the table column headers.
String getResultAsXMLString(String)
--Input a string with the SELECT
statement.
This method returns the result set as an XML string, using SQL names (or aliases) for the XML tags.
Use oracle.jsp.dbutil.CursorBean
for SELECT
, UPDATE
, INSERT
, or DELETE
operations or stored procedure calls on a simple connection. It uses a previously defined ConnBean
object for the connection.
You can specify a SQL operation in a ConnBean
object getCursorBean()
call, or through a call to one of the create()
, execute()
, or executeQuery()
methods of a CursorBean
object as described below.
CursorBean
supports scrollable and updatable cursors, update batching, row prefetching, and query timeout limits. For information about these Oracle JDBC features, see the Oracle9i JDBC Developer's Guide and Reference.
CursorBean
has the following properties:
executeBatch
(batch size for Oracle JDBC update batching)
Setting this property enables Oracle JDBC update batching.
preFetch
(number of statements to prefetch in Oracle JDBC row prefetching)
Setting this property enables Oracle JDBC row prefetching.
queryTimeout
(number of seconds for the driver to wait for a statement to execute before issuing a timeout)
resultSetType
(scrollability of the result set, as indicated by one of the following int
constants):
TYPE_FORWARD_ONLY
(default)--A result set that can scroll only forward (using the next()
method) and is not positionable.
TYPE_SCROLL_INSENSITIVE
--A result set that can scroll forward or backward and is positionable, but is not sensitive to underlying data changes.
TYPE_SCROLL_SENSITIVE
--A result set that can scroll forward or backward, is positionable, and is sensitive to underlying data changes.
See the Oracle9i JDBC Developer's Guide and Reference for information about result set scrollability types.
resultSetConcurrency
(updatability of the result set, as indicated by one of the following int
constants):
CONCUR_READ_ONLY
(default)--A result set that is read-only (cannot be updated).
CONCUR_UPDATABLE
--A result set that is updatable.
See the Oracle9i JDBC Developer's Guide and Reference for information about updatable result sets.
You can set these properties with the following methods to enable Oracle JDBC features, as desired:
void setExecuteBatch(int)
int getExecuteBatch()
void setPreFetch(int)
int getPreFetch()
void setQueryTimeout(int)
int getQueryTimeout()
void setResultSetConcurrency(int)
Specify CursorBean.CONCUR_READ_ONLY
or CursorBean.CONCUR_UPDATABLE
.
int getResultSetConcurrency()
Returns CursorBean.CONCUR_READ_ONLY
or CursorBean.CONCUR_UPDATABLE
.
void setResultSetType(int)
Specify CursorBean.TYPE_FORWARD_ONLY
, CursorBean.TYPE_SCROLL_INSENSITIVE
, or CursorBean.TYPE_SCROLL_SENSITIVE
.
int getResultSetType()
Returns CursorBean.TYPE_FORWARD_ONLY
, CursorBean.TYPE_SCROLL_INSENSITIVE
, or CursorBean.TYPE_SCROLL_SENSITIVE
.
To execute a query once a CursorBean
instance has been defined in a jsp:useBean
statement, you can use CursorBean
methods to create a cursor in one of two ways. You can use the following methods to create the cursor and supply a connection in separate steps:
Or you can combine the process into a single step:
(Set up the ConnBean
object as described in "ConnBean for a Database Connection".)
Then use the following method to specify and execute a query. (This uses a JDBC plain Statement
object behind the scenes.)
Alternatively, if you want to format the result set as an HTML table or XML string, use either of the following methods instead of executeQuery()
:
String getResultAsHTMLTable(String)
Returns a string with HTML statements to create an HTML table for the result set. Specify a string with the SELECT
statement.
String getResultAsXMLString(String)
Returns the result set data in an XML string. Specify a string with the SELECT
statement.
To execute an UPDATE
, INSERT
, or DELETE
statement once a CursorBean
instance has been defined in a jsp:useBean
action, you can use CursorBean
methods to create a cursor in one of two ways. You can use the following methods to create the cursor (specifying a statement type as an integer and SQL statement as a string) and supply a connection:
Or you can combine the process into a single step:
(Set up the ConnBean
object as described in "ConnBean for a Database Connection".)
The int
input takes one of the following constants to specify the type of JDBC statement you want: CursorBean.PLAIN_STMT
(for a Statement
object), CursorBean.PREP_STMT
(for a PreparedStatement
object), or CursorBean.CALL_STMT
(for a CallableStatement
object).
The String
input is to specify the SQL statement.
Then use the following method to execute the INSERT
, UPDATE
, or DELETE
statement. (You can ignore the boolean
return value.)
Or for update batching, use the following method, which returns the number of rows affected. (See below for how to enable update batching.)
int executeUpdate()
Additionally, CursorBean
supports Oracle JDBC functionality such as registerOutParameter()
for callable statements, setXXX()
methods for prepared statements and callable statements, and getXXX()
methods for result sets and callable statements.
Use the following method to close the database cursor:
OracleJSP supplies a custom tag library for SQL functionality (separate from the JML custom tag library).
The following tags are provided:
dbOpen
--Open a database connection.
dbClose
--Close a database connection.
dbQuery
--Execute a query.
dbCloseQuery
--Close the cursor for a query.
dbNextRow
--Process the rows of a result set.
dbExecute
--Execute any SQL statement (DML or DDL).
These tags are described in the following subsections. For examples, see "SQL Tag Examples".
Note the following requirements for using SQL tags:
ojsputil.jar
and include it in your classpath. This file is provided with the OracleJSP installation.
sqltaglib.tld
, is deployed with the application and is in the location specified in the taglib
directives of your JSP pages, such as in the following example:
<%@ taglib uri="/WEB-INF/sqltaglib.tld" prefix="sql" %>
For general information about JSP 1.1 tag library usage, including tag library description files and taglib
directives, see "Standard Tag Library Framework".
Use the dbOpen
tag to open a database connection.
<sql:dbOpen [ connId="connection-id" ] user="username" password="password" URL="databaseURL" > ... </sql:dbOpen>
Nested code that you want to execute through this connection can go into the tag body, between the dbOpen
start and end tags. (See "SQL Tag Examples".) If you use the optional connId
parameter to set a connection identifier, then code to execute through this connection can reference the connection identifier and does not have to be between the dbOpen
start and end tags. (The connection identifier can be any arbitrary string.)
Note that you do not have to hardcode a password into the JSP page (which would be a security concern). Instead, you can get it and other parameters from the request
object, as follows:
<sql:dbOpen connId="conn1" user=<%=request.getParameter("user")%> password=<%=request.getParameter("password")%> URL="url" />
(In this example you do not need a tag body for code that will use this connection; statements using the connection can reference it through the conn1
value of connId
.)
If you set a connection identifier, then the connection is not closed until you close it explicitly with a dbClose
tag. Without a connection identifier, the connection is closed automatically when the </sql:dbOpen>
end tag is encountered.
This tag uses a ConnBean
object for the connection. You can optionally set the additional ConnBean
properties stmtCacheSize
, preFetch
, and batchSize
to enable those Oracle JDBC features. See "ConnBean for a Database Connection" for more information.
Use the dbClose
tag to close a connection associated with the optional connId
parameter specified in a dbOpen
tag. If connId
is not used in the dbOpen
tag, then the connection is closed automatically when the dbOpen
end tag is reached; no dbClose
tag is required.
<sql:dbClose connId="connection-id" />
Note:
In an OracleJSP environment, you can have the connection closed automatically with session-based event handling through the Oracle |
Use the dbQuery
tag to execute a query, outputting the result either as a JDBC result set, HTML table, or XML string. Place the SELECT
statement (one only) in the tag body, between the dbQuery
start and end tags.
<sql:dbQuery [ queryId="query-id" ] [ connId="connection-id" ] [ output="HTML|XML|JDBC"] > ...SELECT statement (one only)... </sql:dbQuery>
All parameters of this tag are optional, depending on your intended uses as described below.
You must use the queryId
parameter to set a query identifier if you want to process the result set using a dbNextRow
tag. The queryId
can be any arbitrary string.
Additionally, if the queryId
parameter is present, then the cursor is not closed until you close it explicitly with a dbCloseQuery
tag. Without a query identifier, the cursor is closed automatically when the </sql:dbQuery>
end tag is encountered.
If connId
is not specified, then dbQuery
must be nested within the body of a dbOpen
tag and will use the connection opened in the dbOpen
tag.
For the output type:
HTML
puts the result set into an HTML table (default).
XML
puts the result set into an XML string.
JDBC
puts the result set into a JDBC ResultSet
object that can be processed using the dbNextRow
tag to iterate through the rows.
This tag uses a CursorBean
object for the cursor. See "CursorBean for DML and Stored Procedures" for information about CursorBean
functionality.
Use the dbCloseQuery
tag to close a cursor associated with the optional queryId
parameter specified in a dbQuery
tag. If queryId
is not used in the dbQuery
tag, then the cursor is closed automatically when the dbQuery
end tag is reached; no dbCloseQuery
tag is required.
<sql:dbCloseQuery queryId="query-id" />
Note:
In an OracleJSP environment, you can have the cursor closed automatically with session-based event handling through the Oracle |
Use the dbNextRow
tag to process each row of a result set obtained in a dbQuery
tag and associated with the specified queryId
. Place the processing code in the tag body, between the dbNextRow
start and end tags. The body is executed for each row of the result set.
For you to use the dbNextRow
tag, the dbQuery
tag must specify output=JDBC
, and specify a queryId
for the dbNextRow
tag to reference.
<sql:dbNextRow queryId="query-id" > ...Row processing... </sql:dbNextRow >
The result set object is created in an instance of the tag-extra-info class of the dbQuery
tag (see "Tag Library Description Files" for information about tag-extra-info classes).
Use the dbExecute
tag to execute any DML or DDL statement (one only). Place the statement in the tag body, between the dbExecute
start and end tags.
<sql:dbExecute [connId="connection-id"] [output="yes|no"] > ...DML or DDL statement (one only)... </sql:dbExecute >
If you do not specify connId
, then you must nest dbExecute
within the body of a dbOpen
tag and use the connection opened in the dbOpen
tag.
If output=yes
, then for DML statements the HTML string "number row[s] affected" will be output to the browser to notify the user how many database rows were affected by the operation; for DDL statements, the statement execution status will be printed. The default setting is no
.
This tag uses a CursorBean
object for the cursor. See "CursorBean for DML and Stored Procedures" for information about CursorBean
functionality.
The following examples show how to use the OracleJSP SQL tags. (To run them yourself, you will need to set the URL, user name, and password appropriately.)
<%@ taglib uri="/WEB-INF/sqltaglib.tld" prefix="sql" %> <HTML> <HEAD> <TITLE>A simple example with open, query, and close tags</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF"> <HR> <sql:dbOpen URL="jdbc:oracle:thin:@dlsun991:1521:816" user="scott" password="tiger" connId="con1"> </sql:dbOpen> <sql:dbQuery connId="con1"> select * from EMP </sql:dbQuery> <sql:dbClose connId="con1" /> <HR> </BODY> </HTML>
<%@ taglib uri="/WEB-INF/sqltaglib.tld" prefix="sql" %> <HTML> <HEAD> <TITLE>Nested Tag with Query inside Open </TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF"> <HR> <sql:dbOpen URL="jdbc:oracle:thin:@dlsun991:1521:816" user="scott" password="tiger"> <sql:dbQuery> select * from EMP </sql:dbQuery> </sql:dbOpen> <HR> </BODY> </HTML>
<%@ page import="oracle.sql.*, oracle.jdbc.driver.*, oracle.jdbc.*, java.sql.*" %> <%@ taglib uri="/WEB-INF/jml.tld" prefix="jml" %> <%@ 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" /> <% } %> <jml:transform href="style/rowset.xsl" > <sql:dbOpen connId="conn1" URL="<%= connStr %>" user="scott" password="tiger"> </sql:dbOpen> <sql:dbQuery connId="conn1" output="xml" queryId="myquery"> select ENAME, EMPNO from EMP </sql:dbQuery> <sql:dbCloseQuery queryId="myquery" /> <sql:dbClose connId="con1" /> </jml:transform>
<%@ taglib uri="/WEB-INF/sqltaglib.tld" prefix="sql" %> <HTML> <HEAD> <TITLE>Result Set Iteration Sample </TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF"> <HR> <sql:dbOpen connId="con1" URL="jdbc:oracle:thin:@dlsun991:1521:816" user="scott" password="tiger"> </sql:dbOpen> <sql:dbQuery connId="con1" output="jdbc" queryId="myquery"> select * from EMP </sql:dbQuery> <sql:dbNextRow queryId="myquery"> <%= myquery.getString(1) %> </sql:dbNextRow> <sql:dbCloseQuery queryId="myquery" /> <sql:dbClose connId="con1" /> <HR> </BODY> </HTML>
This example uses an HTML form to let the user specify what kind of DML or DDL statement to execute.
<%@ taglib uri="/WEB-INF/sqltaglib.tld" prefix="sql" %> <HTML> <HEAD><TITLE>DML Sample</TITLE></HEAD> <FORM METHOD=get> <INPUT TYPE="submit" name="drop" VALUE="drop table test_table"><br> <INPUT TYPE="submit" name="create" VALUE="create table test_table (col1 NUMBER)"><br> <INPUT TYPE="submit" name="insert" VALUE="insert into test_table values (1234)"><br> <INPUT TYPE="submit" name="select" VALUE="select * from test_table"><br> </FORM> <BODY BGCOLOR="#FFFFFF"> Result: <HR> <sql:dbOpen URL="jdbc:oracle:thin:@dlsun991:1521:816" user="scott" password="tiger"> <% if (request.getParameter("drop")!=null) { %> <sql:dbExecute output="yes"> drop table test_table </sql:dbExecute> <% } %> <% if (request.getParameter("create")!=null) { %> <sql:dbExecute output="yes"> create table test_table (col1 NUMBER) </sql:dbExecute> <% } %> <% if (request.getParameter("insert")!=null) { %> <sql:dbExecute output="yes"> insert into test_table values (1234) </sql:dbExecute> <% } %> <% if (request.getParameter("select")!=null) { %> <sql:dbQuery> select * from test_table </sql:dbQuery> <% } %> </sql:dbOpen> <HR> </BODY> </HTML>
The OracleJSP extensions documented in this section are not portable to other JSP environments. This includes the following:
JspScopeListener
mechanism
Notes:
globals.jsa
to support a Web application framework. "OracleJSP Application and Session Support for Servlet 2.0" describes this mechanism.
In standard servlet and JSP technology, only session-based events are supported. OracleJSP extends this support through the JspScopeListener
interface and JspScopeEvent
class in the oracle.jsp.event
package. The OracleJSP mechanism supports the four standard JSP scopes for event-handling for any Java objects used in a JSP application:
For Java objects that are used 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 so notified. The OracleJSP 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
The OracleJSP 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, see "Page Using JspScopeListener--scope.jsp".
SQLJ is a standard syntax for embedding static SQL instructions directly in Java code, greatly simplifying database-access programming. OracleJSP and the OracleJSP translator support Oracle SQLJ, allowing you to use SQLJ syntax in JSP statements. SQLJ statements are indicated by the #sql
token.
For general information about Oracle SQLJ programming features, syntax, and command-line options, see the Oracle9i SQLJ Developer's Guide and Reference.
Following is a sample SQLJ JSP page. (The page
directive imports classes that are typically required by SQLJ.)
<%@ page language="sqlj" import="sqlj.runtime.ref.DefaultContext,oracle.sqlj.runtime.Oracle" %> <HTML> <HEAD> <TITLE> The SQLJQuery JSP </TITLE> </HEAD> <BODY BGCOLOR="white"> <% String empno = request.getParameter("empno"); if (empno != null) { %> <H3> Employee # <%=empno %> Details: </H3> <%= runQuery(empno) %> <HR><BR> <% } %> <B>Enter an employee number:</B> <FORM METHOD="get"> <INPUT TYPE="text" NAME="empno" SIZE=10> <INPUT TYPE="submit" VALUE="Ask Oracle"); </FORM> </BODY> </HTML> <%! private String runQuery(String empno) throws java.sql.SQLException { DefaultContext dctx = null; String ename = null; double sal = 0.0; String hireDate = null; StringBuffer sb = new StringBuffer(); try { dctx = Oracle.getConnection("jdbc:oracle:oci8:@", "scott", "tiger"); #sql [dctx] { select ename, sal, TO_CHAR(hiredate,'DD-MON-YYYY') INTO :ename, :sal, :hireDate FROM scott.emp WHERE UPPER(empno) = UPPER(:empno) }; sb.append("<BLOCKQUOTE><BIG><B><PRE>\n"); sb.append("Name : " + ename + "\n"); sb.append("Salary : " + sal + "\n"); sb.append("Date hired : " + hireDate); sb.append("</PRE></B></BIG></BLOCKQUOTE>"); } catch (java.sql.SQLException e) { sb.append("<P> SQL error: <PRE> " + e + " </PRE> </P>\n"); } finally { if (dctx!= null) dctx.close(); } return sb.toString(); } %>
This example uses the JDBC OCI driver, which requires an Oracle client installation. The Oracle
class used in getting the connection is provided with Oracle SQLJ.
Entering employee number 7788 for the schema used in the example results in the following output:
For further examples of using SQLJ in JSP pages, see "SQLJ Queries--SQLJSelectInto.sqljsp and SQLJIterator.sqljsp".
You can trigger the OracleJSP translator to invoke the Oracle SQLJ translator by using the file name extension .sqljsp
for the JSP source file.
This results in the OracleJSP translator generating a .sqlj
file instead of a .java
file. The Oracle SQLJ translator is then invoked to translate the .sqlj
file into a .java
file.
Using SQLJ results in additional output files; see "Generated Files and Locations (On-Demand Translation)".
Important:
|
When you execute or pre-translate a SQLJ JSP page, you can specify desired Oracle SQLJ option settings. This is true both in on-demand translation scenarios and pre-translation scenarios, as follows:
sqljcmd
configuration parameter. This parameter, in addition to allowing you to specify a particular SQLJ translator executable, allows you to set SQLJ command-line options. (The sqljcmd
parameter was not available prior to OracleJSP release 1.1.0.0.0.)
For information, see the sqljcmd
description in "OracleJSP Configuration Parameters (Non-OSE)". For how to set configuration parameters, see "OracleJSP Configuration Parameter Settings".
ojspc
pre-translation tool, use the ojspc -S
option. This option allows you to set SQLJ command-line options.
For information, see "Command-Line Syntax for ojspc" and "Option Descriptions for ojspc".
OracleJSP defines a file, globals.jsa
, as a mechanism for implementing the JSP specification in a servlet 2.0 environment. Web applications and servlet contexts were not fully defined in the servlet 2.0 specification.
This section discusses the globals.jsa
mechanism and covers the following topics:
For sample applications, see "Samples Using globals.jsa for Servlet 2.0 Environments".
Within any single Java virtual machine, you can use a globals.jsa
file for each application (or, equivalently, for each servlet context). This file supports the concept of Web applications in the following areas:
The globals.jsa
file also provides a vehicle for global Java declarations and JSP directives across all JSP pages of an application.
To deploy an OracleJSP application that does not incorporate servlets, copy the directory structure into the Web server and create a file called globals.jsa
to place at the application root directory.
The globals.jsa
file can be of zero size. The OracleJSP container will locate it, and its presence in a directory defines that directory (as mapped from the URL virtual path) as the root directory of the application.
OracleJSP also defines default locations for JSP application resources. For example, application beans and classes in the application-relative /WEB-INF/classes
and /WEB-INF/lib
directories will automatically be loaded by the OracleJSP classloader without the need for specific configuration.
The servlet 2.0 specification does not have a clearly defined concept of a Web application and there is no defined relationship between servlet contexts and applications, as there is in later servlet specifications. In a servlet 2.0 environment such as Apache/JServ, there is only one servlet context object per JVM. A servlet 2.0 environment also has only one session object.
The globals.jsa
file, however, provides support for multiple applications and multiple sessions in a Web server, particularly for use in a servlet 2.0 environment.
Where a distinct servlet context object would not otherwise be available for each application, the presence of a globals.jsa
file for an application allows the OracleJSP container to provide the application with a distinct ServletContext
object.
Additionally, where there would otherwise be only one session object (with either one servlet context or across multiple servlet contexts), the presence of a globals.jsa
file allows the OracleJSP container to provide a proxy HttpSession
object to the application. This prevents the possibility of session variable-name collisions with other applications, although unfortunately it cannot protect application data from being inspected or modified by other applications. This is because HttpSession
objects must rely on the underlying servlet session environment for some of their functionality.
An application must be notified when a significant state transition occurs. For example, applications often want to acquire resources when an HTTP session begins and release resources when the session ends, or restore or save persistent data when the application itself is started or terminated.
In standard servlet and JSP technology, however, only session-based events are supported.
For applications that use a globals.jsa
file, OracleJSP extends this functionality with the following four events:
You can write event handlers in the globals.jsa
file for any of these events that the server should respond to.
The session_OnStart
event and session_OnEnd
event are triggered at the beginning and end of an HTTP session, respectively.
The application_OnStart
event is triggered for any application by the first request for that application within any single JVM. The application_OnEnd
event is triggered when the OracleJSP container unloads an application.
For more information, see "The globals.jsa Event Handlers".
This section is an overview of general syntax and semantics for a globals.jsa
file.
Each event block in a globals.jsa
file--a session_OnStart
block, a session_OnEnd
block, an application_OnStart
block, or an application_OnEnd
block--has an event start tag, an event end tag, and a body (everything between the start and end tags) that includes the event-handler code.
The following example shows this pattern:
<event:session_OnStart> <% This scriptlet contains the implementation of the event handler %> </event:session_OnStart>
The body of an event block can contain any valid JSP tags--standard tags as well as tags defined in a custom tag library.
The scope of any JSP tag in an event block, however, is limited to only that block. For example, a bean that is declared in a jsp:useBean
tag within one event block must be redeclared in any other event block that uses it. You can avoid this restriction, however, through the globals.jsa
global declaration mechanism--see "Global Declarations and Directives".
For details about each of the four event handlers, see "The globals.jsa Event Handlers".
JSP implicit objects are available in globals.jsa
event blocks as follows:
application_OnStart
block has access to the application
object.
application_OnEnd
block has access to the application
object.
session_OnStart
block has access to the application
, session
, request
, response
, page
, and out
objects.
session_OnEnd
block has access to the application
and session
objects.
This example shows you a complete globals.jsa
file, using all four event handlers.
<event:application_OnStart> <%-- Initializes counts to zero --%> <jsp:useBean id="pageCount" class="oracle.jsp.jml.JmlNumber" scope = "application" /> <jsp:useBean id="sessionCount" class="oracle.jsp.jml.JmlNumber" scope = "application" /> <jsp:useBean id="activeSessions" class="oracle.jsp.jml.JmlNumber" scope = "application" /> </event:application_OnStart> <event:application_OnEnd> <%-- Acquire beans --%> <jsp:useBean id="pageCount" class="oracle.jsp.jml.JmlNumber" scope = "application" /> <jsp:useBean id="sessionCount" class="oracle.jsp.jml.JmlNumber" scope = "application" /> <% application.log("The number of page hits were: " + pageCount.getValue() ); %> <% application.log("The number of client sessions were: " + sessionCount.getValue() ); %> </event:application_OnEnd> <event:session_OnStart> <%-- Acquire beans --%> <jsp:useBean id="sessionCount" class="oracle.jsp.jml.JmlNumber" scope = "application" /> <jsp:useBean id="activeSessions" class="oracle.jsp.jml.JmlNumber" scope = "application" /> <% sessionCount.setValue(sessionCount.getValue() + 1); activeSessions.setValue(activeSessions.getValue() + 1); %> <br> Starting session #: <%=sessionCount.getValue() %> <br> There are currently <b> <%= activeSessions.getValue() %> </b> active sessions <p> </event:session_OnStart> <event:session_OnEnd> <%-- Acquire beans --%> <jsp:useBean id="activeSessions" class="oracle.jsp.jml.JmlNumber" scope = "application" /> <% activeSessions.setValue(activeSessions.getValue() - 1); %> </event:session_OnEnd>
This section provides details about each of the four globals.jsa
event handlers.
The application_OnStart
block has the following general syntax:
<event:application_OnStart> <% This scriptlet contains the implementation of the event handler %> </event:application_OnStart>
The body of the application_OnStart
event handler is executed when OracleJSP loads the first JSP page in the application. This usually occurs when the first HTTP request is made to any page in the application, from any client. Applications use this event to initialize application-wide resources, such as a database connection pool or data read from a persistent repository into application objects.
The event handler must contain only JSP tags (including custom tags) and white space--it cannot contain static text.
Errors that occur in this event handler but are not processed in the event-handler code are automatically trapped by the OracleJSP container and logged using the servlet context of the application. Event handling then proceeds as if no error had occurred.
The following application_OnStart
example is from the "globals.jsa Example for Application Events--lotto.jsp". In this example, the generated lottery numbers for a particular user are cached for an entire day. If the user re-requests the picks, he or she gets the same set of numbers. The cache is recycled once a day, giving each user a new set of picks. To function as intended, the lotto application must make the cache persistent when the application is being shut down, and must refresh the cache when the application is reactivated.
The application_OnStart
event handler reads the cache from the lotto.che
file.
<event:application_OnStart> <% Calendar today = Calendar.getInstance(); application.setAttribute("today", today); try { FileInputStream fis = new FileInputStream (application.getRealPath("/")+File.separator+"lotto.che"); ObjectInputStream ois = new ObjectInputStream(fis); Calendar cacheDay = (Calendar) ois.readObject(); if (cacheDay.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) { cachedNumbers = (Hashtable) ois.readObject(); application.setAttribute("cachedNumbers", cachedNumbers); } ois.close(); } catch (Exception theE) { // catch all -- can't use persistent data } %> </event:application_OnStart>
The application_OnEnd
block has the following general syntax:
<event:application_OnEnd> <% This scriptlet contains the implementation of the event handler %> </event:application_OnEnd>
The body of the application_OnEnd
event handler is executed when OracleJSP unloads the JSP application. Unloading occurs whenever a previously loaded page is reloaded after on-demand dynamic re-translation (unless the OracleJSP unsafe_reload
configuration parameter is enabled), or when the OracleJSP container, which itself is a servlet, is terminated by having its destroy()
method called by the underlying servlet container. Applications use the application_OnEnd
event to clean up application level resources or to write application state to a persistent store.
The event handler must contain only JSP tags (including custom tags) and white space--it cannot contain static text.
Errors that occur in this event handler but are not processed in the event-handler code are automatically trapped by the OracleJSP container and logged using the servlet context of the application. Event handling then proceeds as if no error had occurred.
The following application_OnEnd
example is from the "globals.jsa Example for Application Events--lotto.jsp". In this event handler, the cache is written to file lotto.che
before the application is terminated.
<event:application_OnEnd> <% Calendar now = Calendar.getInstance(); Calendar today = (Calendar) application.getAttribute("today"); if (cachedNumbers.isEmpty() || now.get(Calendar.DAY_OF_YEAR) > today.get(Calendar.DAY_OF_YEAR)) { File f = new File(application.getRealPath("/")+File.separator+"lotto.che"); if (f.exists()) f.delete(); return; } try { FileOutputStream fos = new FileOutputStream (application.getRealPath("/")+File.separator+"lotto.che"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(today); oos.writeObject(cachedNumbers); oos.close(); } catch (Exception theE) { // catch all -- can't use persistent data } %> </event:application_OnEnd>
The session_OnStart
block has the following general syntax:
<event:session_OnStart> <% This scriptlet contains the implementation of the event handler %> Optional static text... </event:session_OnStart>
The body of the session_OnStart
event handler is executed when OracleJSP creates a new session in response to a JSP page request. This occurs on a per client basis, whenever the first request is received for a session-enabled JSP page in an application.
Applications might use this event for the following purposes:
Because the implicit out
object is available to session_OnStart
, this is the only globals.jsa
event handler that can contain static text in addition to JSP tags.
The session_OnStart
event handler is called before the code of the JSP page is executed. As a result, output from session_OnStart
precedes any output from the page.
The session_OnStart
event handler and the JSP page that triggered the event share the same out
stream. The buffer size of this stream is controlled by the buffer size of the JSP page. The session_OnStart
event handler does not automatically flush the stream to the browser--the stream is flushed according to general JSP rules. Headers can still be written in JSP pages that trigger the session_OnStart
event.
Errors that occur in this event handler but are not processed in the event-handler code are automatically trapped by the OracleJSP container and logged using the servlet context of the application. Event handling then proceeds as if no error had occurred.
The following example makes sure that each new session starts on the initial page (index.jsp
) of the application.
<event:session_OnStart> <% if (!page.equals("index.jsp")) { %> <jsp:forward page="index.jsp" /> <% } %> </event:session_OnStart>
The session_OnEnd
block has the following general syntax:
<event:session_OnEnd> <% This scriptlet contains the implementation of the event handler %> </event:session_OnEnd>
The body of the session_OnEnd
event handler is executed when OracleJSP invalidates an existing session. This occurs in either of the following circumstances:
session.invalidate()
method.
Applications use this event to release client resources.
The event handler must contain only JSP tags (including tag library tags) and white space--it cannot contain static text.
Errors that occur in this event handler but are not processed in the event-handler code are automatically trapped by the OracleJSP container and logged using the servlet context of the application. Event handling then proceeds as if no error had occurred.
The following example decrements the "active session" count when a session is terminated.
<event:session_OnEnd> <%-- Acquire beans --%> <jsp:useBean id="activeSessions" class="oracle.jsp.jml.JmlNumber" scope = "application" /> <% activeSessions.setValue(activeSessions.getValue() - 1); %> </event:session_OnEnd>
In addition to holding event handlers, a globals.jsa
file can be used to globally declare directives and objects for the JSP application. You can include JSP directives, JSP declarations, JSP comments, and JSP tags that have a scope
parameter (such as jsp:useBean
).
This section covers the following topics:
Directives used within a globals.jsa
file serve a dual purpose:
globals.jsa
file itself.
A directive in a globals.jsa
file becomes an implicit directive for all JSP pages in the application, although a globals.jsa
directive can be overwritten for any particular page.
A globals.jsa
directive is overwritten in a JSP page on an attribute-by-attribute basis. If a globals.jsa
file has the following directive:
<%@ page import="java.util.*" bufferSize="10kb" %>
and a JSP page has the following directive:
<%@page bufferSize="20kb" %>
then this would be equivalent to the page having the following directive:
<%@ page import="java.util.*" bufferSize="20kb" %>
If you want to declare a method or data member to be shared across any of the event handlers in a globals.jsa
file, use a JSP <%!... %>
declaration within the globals.jsa
file.
Note that JSP pages in the application do not have access to these declarations, so you cannot use this mechanism to implement an application library. Declaration support is provided in the globals.jsa
file for common functions to be shared across event handlers.
Probably the most common elements declared in globals.jsa
files are global objects. Objects declared in a globals.jsa
file become part of the implicit object environment of the globals.jsa
event handlers and all the JSP pages in the application.
An object declared in a globals.jsa
file (such as by a jsp:useBean
statement) does not need to be redeclared in any of the individual JSP pages of the application.
You can declare a global object using any JSP tag or extension that has a scope
parameter, such as jsp:useBean
or jml:useVariable
. Globally declared objects must be of either session
or application
scope (not page
or request
scope).
Nested tags are supported. Thus, a jsp:setProperty
command can be nested in a jsp:useBean
declaration. (A translation error occurs if jsp:setProperty
is used outside a jsp:useBean
declaration.)
When a global object is used in a globals.jsa
event handler, the position of its declaration is important. Only those objects that are declared before a particular event handler are added as implicit objects to that event handler. For this reason, developers are advised to structure their globals.jsa
file in the following sequence:
The sample globals.jsa
file below accomplishes the following:
globals.jsa
file, as well as for all subsequent pages.
By including the taglib
directive in the globals.jsa
file, the directive does not have to be included in any of the individual JSP pages of the application.
jsp:useBean
statements).
For an additional example of using globals.jsa
for global declarations, see "globals.jsa Example for Global Declarations--index2.jsp".
<%-- Directives at the top --%> <%@ taglib uri="oracle.jsp.parse.OpenJspRegisterLib" prefix="jml" %> <%-- Declare global objects here --%> <%-- Initializes counts to zero --%> <jsp:useBean id="pageCount" class="oracle.jsp.jml.JmlNumber" scope = "application" /> <jsp:useBean id="sessionCount" class="oracle.jsp.jml.JmlNumber" scope = "application" /> <jsp:useBean id="activeSessions" class="oracle.jsp.jml.JmlNumber" scope = "application" /> <%-- Application lifecycle event handlers go here --%> <event:application_OnStart> <% This scriptlet contains the implementation of the event handler %> </event:application_OnStart> <event:application_OnEnd> <% This scriptlet contains the implementation of the event handler %> </event:application_OnEnd> <event:session_OnStart> <% This scriptlet contains the implementation of the event handler %> </event:session_OnStart> <event:session_OnEnd> <% This scriptlet contains the implementation of the event handler %> </event:session_OnEnd> <%-- Declarations used by the event handlers go here --%>
|
Copyright © 1996-2001, Oracle Corporation. All Rights Reserved. |
|