servlet

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » EJB Server GlassFish » servlet 
glassfish: servlet
License:
URL:https://glassfish.dev.java.net//
Description:
Package NameComment
javax.el Provides the API for the Unified Expression Language shared by the JSP 2.1 and JSF 1.2 technologies.

The Expression Language (EL) is a simple language designed to satisfy the specific needs of web application developers. It is currently defined in its own specification document within the JavaServer Pages (tm) (JSP) 2.1 specification, but does not have any dependencies on any portion of the JSP 2.1 specification. It is intended for general use outside of the JSP and JSF specifications as well.

This package contains the classes and interfaces that describe and define the programmatic access to the Expression Language engine. The API is logically partitioned as follows:

EL Context

An important goal of the EL is to ensure it can be used in a variety of environments. It must therefore provide enough flexibility to adapt to the specific requirements of the environment where it is being used.

Class {@link javax.el.ELContext} is what links the EL with the specific environment where it is being used. It provides the mechanism through which all relevant context for creating or evaluating an expression is specified.

Creation of ELContext objects is controlled through the underlying technology. For example, in JSP, the JspContext.getELContext() factory method is used.

Some technologies provide the ability to add an {@link javax.el.ELContextListener} so that applications and frameworks can ensure their own context objects are attached to any newly created ELContext.

Expression Objects

At the core of the Expression Language is the notion of an expression that gets parsed according to the grammar defined by the Expression Language.

There are two types of expressions defined by the EL: value expressions and method expressions. A {@link javax.el.ValueExpression} such as "${customer.name}" can be used either as an rvalue (return the value associated with property name of the model object customer) or as an lvalue (set the value of the property name of the model object customer).

A {@link javax.el.MethodExpression} such as "${handler.process}" makes it possible to invoke a method (process) on a specific model object (handler).

All expression classes extend the base class {@link javax.el.Expression}, making them serializable and forcing them to implement equals() and hashCode(). Morevover, each method on these expression classes that actually evaluates an expression receives a parameter of class {@link javax.el.ELContext}, which provides the context required to evaluate the expression.

Creation of Expressions

An expression is created through the {@link javax.el.ExpressionFactory} class. The factory provides two creation methods; one for each type of expression supported by the EL.

To create an expression, one must provide an {@link javax.el.ELContext}, a string representing the expression, and the expected type (ValueExpression) or signature (MethodExpression). The ELContext provides the context necessary to parse an expression. Specifically, if the expression uses an EL function (for example ${fn:toUpperCase(customer.name)}) or an EL variable, then {@link javax.el.FunctionMapper} and {@link javax.el.VariableMapper} objects must be available within the ELContext so that EL functions and EL variables are properly mapped.

Resolution of Model Objects and their Properties

Through the {@link javax.el.ELResolver} base class, the EL features a pluggable mechanism to resolve model object references as well as properties of these objects.

The EL API provides implementations of ELResolver supporting property resolution for common data types which include arrays ({@link javax.el.ArrayELResolver}), JavaBeans ({@link javax.el.BeanELResolver}), Lists ({@link javax.el.ListELResolver}), Maps ({@link javax.el.MapELResolver}), and ResourceBundles ({@link javax.el.ResourceBundleELResolver}).

Tools can easily obtain more information about resolvable model objects and their resolvable properties by calling method getFeatureDescriptors on the ELResolver. This method exposes objects of type java.beans.FeatureDescriptor, providing all information of interest on top-level model objects as well as their properties.

EL Functions

If an EL expression uses a function (for example ${fn:toUpperCase(customer.name)}), then a {@link javax.el.FunctionMapper} object must also be specified within the ELContext. The FunctionMapper is responsible to map ${prefix:name()} style functions to static methods that can execute the specified functions.

EL Variables

Just like {@link javax.el.FunctionMapper} provides a flexible mechanism to add functions to the EL, {@link javax.el.VariableMapper} provides a flexible mechanism to support the notion of EL variables.

An EL variable does not directly refer to a model object that can then be resolved by an ELResolver. Instead, it refers to an EL expression. The evaluation of that EL expression gives the EL variable its value.

For example, in the following code snippet

<h:inputText value="#{handler.customer.name}"/>
handler refers to a model object that can be resolved by an EL Resolver.

However, in this other example:

<c:forEach var="item" items="#{model.list}">
   <h:inputText value="#{item.name}"/>
</c:forEach>
item is an EL variable because it does not refer directly to a model object. Instead, it refers to another EL expression, namely a specific item in the collection referred to by the EL expression #{model.list}.

Assuming that there are three elements in ${model.list}, this means that for each invocation of <h:inputText>, the following information about item must be preserved in the {@link javax.el.VariableMapper}:

first invocation: item maps to first element in ${model.list}
second invocation: item maps to second element in ${model.list}
third invocation: item maps to third element in ${model.list}

VariableMapper provides the mechanisms required to allow the mapping of an EL variable to the EL expression from which it gets its value.

javax.servlet The javax.servlet package contains a number of classes and interfaces that describe and define the contracts between a servlet class and the runtime environment provided for an instance of such a class by a conforming servlet container.
javax.servlet.http The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts between a servlet class running under the HTTP protocol and the runtime environment provided for an instance of such a class by a conforming servlet container.
javax.servlet.jsp Classes and interfaces for the Core JSP 2.1 API.

The javax.servlet.jsp package contains a number of classes and interfaces that describe and define the contracts between a JSP page implementation class and the runtime environment provided for an instance of such a class by a conforming JSP container.

JSP Page Implementation Object Contract

This section describes the basic contract between a JSP Page implementation object and its container.

The main contract is defined by the classes {@link javax.servlet.jsp.JspPage} and {@link javax.servlet.jsp.HttpJspPage}. The {@link javax.servlet.jsp.JspFactory} class describes the mechanism to portably instantiate all needed runtime objects, and {@link javax.servlet.jsp.JspEngineInfo} provides basic information on the current JSP container. Class {@link javax.servlet.jsp.JspApplicationContext} stores application-scoped information relevant to JSP containers. It was added in JSP 2.1 to support the integration of the unified Expression Language.

None of these classes are intended to be used by JSP page authors; an example of how these classes may be used is included below.

Implicit Objects

The {@link javax.servlet.jsp.PageContext} object and the {@link javax.servlet.jsp.JspWriter} are available by default as implicit objects.

Exceptions

The {@link javax.servlet.jsp.JspException} class is the base class for all JSP exceptions. The {@link javax.servlet.jsp.JspTagException} and {@link javax.servlet.jsp.SkipPageException} exceptions are used by the tag extension mechanism.

For JSP error pages, the {@link javax.servlet.jsp.ErrorData} class encapsulates information about the error.

An Implementation Example

An instance of an implementation dependent subclass of the {@link javax.servlet.jsp.PageContext} abstract base class can be created by a JSP implementation class at the beginning of it's _jspService() method via an implementation default {@link javax.servlet.jsp.JspFactory}.

Here is one example of how to use these classes

 public class foo implements Servlet {

 // ...

public void _jspService(HttpServletRequest request,
			HttpServletResponse response)
       throws IOException, ServletException {

    JspFactory  factory     = JspFactory.getDefaultFactory();
    PageContext pageContext = factory.getPageContext(
					this,
					request,
					response,
					null,  // errorPageURL
					false, // needsSession
					JspWriter.DEFAULT_BUFFER,
					true   // autoFlush
			        );

    // initialize implicit variables for scripting env ...

    HttpSession session = pageContext.getSession();
    JspWriter   out     = pageContext.getOut();
    Object      page    = this;

    try {
        // body of translated JSP here ...
    } catch (Exception e) {
        out.clear();
        pageContext.handlePageException(e);
    } finally {
        out.close();
	  factory.releasePageContext(pageContext);
    }
}
javax.servlet.jsp.el Provides the ELResolver classes that define the object resolution rules that must be supported by a JSP container with the new unified Expression Language.

The package also defines programmatic access to the old Expression Language evaluator (pre JSP 2.1).

Please note that as of JSP 2.1, all classes and interfaces that were in package javax.servlet.jsp.el have been deprecated in favor of the new unified Expression Language APIs (javax.el). See the Expression Language specification document for more details.

While a JSP container must still support the deprecated APIs defined in javax.servlet.jsp.el, developers should only rely on the new javax.el APIs for new development work.

Two ELResolver classes have been added in JSP 2.1 to implement object resolution rules that must be supported by a JSP container with the new unified Expression Language: {@link javax.servlet.jsp.el.ImplicitObjectELResolver} and {@link javax.servlet.jsp.el.ScopedAttributeELResolver}.

Documentation on the old and deprecated API

The JavaServer Pages(tm) (JSP) 2.0 specification provides a portable API for evaluating "EL Expressions". As of JSP 2.0, EL expressions can be placed directly in the template text of JSP pages and tag files.

This package contains a number of classes and interfaces that describe and define programmatic access to the Expression Language evaluator. This API can also be used by an implementation of JSP to evaluate the expressions, but other implementations, like open-coding into Java bytecodes, are allowed. This package is intended to have no dependencies on other portions of the JSP 2.0 specification.

Expression Evaluator

Programmatic access to the EL Expression Evaluator is provided through the following types:
  • ExpressionEvaluator
  • Expression
  • FunctionMapper
  • VariableResolver

An ExpressionEvaluator object can be obtained from a JspContext object through the getExpressionEvaluator method. An ExpressionEvaluator encapsulates the EL processor. An EL expression provided as a String can then be evaluated directly, or it can be parsed first into an Expression object. The parse step, can be used to factor out the cost of parsing the expression, or even the cost of optimizing the implementation.

The parsing of an expression string is done against a target type, a default prefix (that applies when a function has no prefix), and a FunctionMapper. The FunctionMapper object maps a prefix and a local name part into a java.lang.reflect.Method object.

The interpretation or evaluation of a parsed expression is done using a VariableResolver object. This object resolves top level object names into Objects. A VariableResolver can be obtained from a JspContext object through the getVariableResolver method.

Exceptions

The ELException exception is used by the expression language to denote any exception that may arise during the parsing or evaluation of an expression. The ELParseException exception is a subclass of ELException that corresponds to parsing errors

Parsing errors are conveyed as exceptions to simplify the API. It is expected that many JSP containers will use additional mechanisms to parse EL expressions and report their errors - a run-time API cannot provide accurate line-error numbers without additional machinery.

Code Fragment

Below is a non-normative code fragment outlining how the APIs can be used.

// Get an instance of an ExpressionEvaluator


ExpressionEvaluator ee = myJspContext.getExpressionEvaluator();
VariableResolver vr = myJspContext.getVariableResolver();

FunctionMapper fm; // we don't have a portable implementation yet

// Example of compiling an expression.  See [ISSUE-2]
// Errors detected this way may have higher quality than those
// found with a simple validate() invocation.

ExpressionCompilation ce;

try {
  ce = ee.prepareExpression(expr,
			    targetClass,
			    fm,
			    null // no prefixes
			    );
} catch (ELParseException e) {
	log (e.getMessage());
}

try {
  ce.evaluate(vr);
} catch (ElException e) {
	log (e);
}
javax.servlet.jsp.tagext Classes and interfaces for the definition of JavaServer Pages Tag Libraries.

Custom actions can be used by JSP authors and authoring tools to simplify writing JSP pages. A custom action can be either an empty or a non-empty action.

An empty tag has no body. There are two equivalent syntaxes, one with separate start and end tags, and one where the start and end tags are combined. The two following examples are identical:

<x:foo att="myObject"></foo>
<x:foo att="myObject"/>

A non-empty tag has a start tag, a body, and an end tag. A prototypical example is of the form:

<x:foo att="myObject" >
  BODY
</x:foo/>

The JavaServer Pages(tm) (JSP) specification provides a portable mechanism for the description of tag libraries.

A JSP tag library contains

  • A Tag Library Descriptor
  • A number of Tag Files or Tag handler classes defining request-time behavior
  • Additional classes and resources used at runtime
  • Possibly some additional classes to provide extra translation information

This API is described in the following sections:

  1. Classic Tag Handlers
  2. Tag Handlers that want to access their Body Content
  3. Dynamic Attributes
  4. Annotated Tag Handler Management Example
  5. Cooperating Actions
  6. Simple Tag Handlers
  7. JSP Fragments
  8. Example Simple Tag Handler Scenario
  9. Translation-time Classes

1. Classic Tag Handlers

This section introduces the notion of a tag handler and describes the classic types of tag handler.

JSP 2.0 introduces a new type of Tag Handler called a Simple Tag Handler, which is described in a later section. The protocol for Simple Tag handlers is much more straightforward.

Tag Handler

A tag handler is a run-time, container-managed object that evaluates custom actions during the execution of a JSP page. A tag handler supports a protocol that allows the JSP container to provide good integration of the server-side actions within a JSP page.

A tag handler is created initially using a zero argument constructor on its corresponding class; the method java.beans.Beans.instantiate() is not used.

A tag handler has some properties that are exposed to the page as attributes on an action; these properties are managed by the JSP container (via generated code). The setter methods used to set the properties are discovered using the JavaBeans introspector machinery.

The protocol supported by a tag handler provides for passing of parameters, the evaluation and reevaluation of the body of the action, and for getting access to objects and other tag handlers in the JSP page.

A tag handler instance is responsible for processing one request at a time. It is the responsability of the JSP container to enforce this.

Additional translation time information associated with the action indicates the name of any scripting variables it may introduce, their types and their scope. At specific moments, the JSP container will automatically synchronize the {@link javax.servlet.jsp.PageContext} information with variables in the scripting language so they can be made available directly through the scripting elements.

Properties

A tag handler has some properties. All tag handlers have a pageContext property for the JSP page where the tag is located, and a parent property for the tag handler to the closest enclosing action. Specific tag handler classes may have additional properties.

All attributes of a custom action must be JavaBeans component properties, although some properties may not be exposed as attributes. The attributes that are visible to the JSP translator are exactly those listed in the Tag Library Descriptor (TLD).

All properties of a tag handler instance exposed as attributes will be initialized by the container using the appropriate setter methods before the instance can be used to perform the action methods. It is the responsibility of the JSP container to invoke the appropriate setter methods to initialize these properties. It is the responsability of user code, be it scriptlets, JavaBeans code, or code inside custom tags, to not invoke these setter methods, as doing otherwise would interfere with the container knowledge.

The setter methods that should be used when assigning a value to an attribute of a custom action are determined by using the JavaBeans introspector on the tag handler class, then use the setter method associated with the property that has the same name as the attribute in question. An implication (unclear in the JavaBeans specification) is that there is only one setter per property.

Unspecified attributes/properties should not be set (using a setter method).

Once properly set, all properties are expected to be persistent, so that if the JSP container ascertains that a property has already been set on a given tag handler instance, it must not set it again.

The JSP container may reuse classic tag handler instances for multiple occurrences of the corresponding custom action, in the same page or in different pages, but only if the same set of attributes are used for all occurrences. If a tag handler is used for more than one occurence, the container must reset all attributes where the values differ between the custom action occurrences. Attributes with the same value in all occurrences must not be reset. If an attribute value is set as a request-time attribute value (using a scripting or an EL expression), the container must reset the attribute between all reuses of the tag handler instance.

User code can access property information and access and modify tag handler internal state starting with the first action method (doStartTag) up until the last action method (doEndTag or doFinally for tag handlers implementing TryCatchFinally).

Tag Handler as a Container-Managed Object

Since a tag handler is a container managed object, the container needs to maintain its references; specifically, user code should not keep references to a tag handler except between the start of the first action method (doStartTag()) and the end of the last action method (doEndTag() or doFinally() for those tags that implement TryCatchFinally).

The restrictions on references to tag handler objects and on modifying attribute properties gives the JSP container substantial freedom in effectively managing tag handler objects to achieve different goals. For example, a container may implementing different pooling strategies to minimize creation cost, or may hoist setting of properties to reduce cost when a tag handler is inside another iterative tag.

Conversions

A tag handler implements an action; the JSP container must follow the type conversions described in Section 2.13.2 when assigning values to the attributes of an action.

Empty and Non-Empty Actions

An empty action has no body; it may use one of two syntaxes: either <foo/> or <foo></foo>. Since empty actions have no body the methods related to body manipulation are not invoked. There is a mechanism in the Tag Library Descriptor to indicate that a tag can only be used to write empty actions; when used, non-empty actions using that tag will produce a translation error.

A non-empty action has a body.

The Tag Interface

A Tag handler that does not want to process its body can implement just the Tag interface. A tag handler may not want to process its body because it is an empty tag or because the body is just to be "passed through".

The Tag interface includes methods to provide page context information to the Tag Handler instance, methods to handle the life-cycle of tag handlers, and two main methods for performing actions on a tag: doStartTag() and doEndTag(). The method doStartTag() is invoked when encountering the start tag and its return value indicates whether the body (if there is any) should be skipped, or evaluated and passed through to the current response stream. The method doEndTag() is invoked when encountering the end tag; its return value indicates whether the rest of the page should continue to be evaluated or not.

If an exception is encountered during the evaluation of the body of a tag, its doEndTag method will not be evaluated. See the TryCatchFinally tag for methods that are guaranteed to be evaluated.

The IterationTag Interface

The IterationTag interface is used to repeatedly reevaluate the body of a custom action. The interface has one method: doAfterBody() which is invoked after each evaluation of the body to determine whether to reevaluate or not.

Reevaluation is requested with the value 2, which in JSP 1.1 is defined to be BodyTag.EVAL_BODY_TAG. That constant value is still kept in JSP 1.2 (for full backwards compatibility) but, to improve clarity, a new name is also available: IterationTag.EVAL_BODY_AGAIN. To stop iterating, the returned value should be 0, which is Tag.SKIP_BODY.

The JspIdConsumer Interface

This interface indicates to the container that a tag handler wishes to be provided with a compiler generated ID that is unique within the page.

The TagSupport Base Class

The TagSupport class is a base class that can be used when implementing the Tag or IterationTag interfaces.

2. Tag Handlers that want Access to their Body Content

The evaluation of a body is delivered into a BodyContent object. This is then made available to tag handlers that implement the BodyTag interface. The BodyTagSupport class provides a useful base class to simplify writing these handlers.

If a Tag handler wants to have access to the content of its body then it must implement the BodyTag interface. This interface extends IterationTag, provides two additional methods setBodyContent(BodyContent) and doInitBody() and refers to an object of type BodyContent.

A BodyContent is a subclass of JspWriter that has a few additional methods to convert its contents into a String, insert the contents into another JspWriter, to get a Reader into its contents, and to clear the contents. Its semantics also assure that buffer size will never be exceeded.

The JSP page implementation will create a BodyContent if the doStartTag() method returns a EVAL_BODY_BUFFERED. This object will be passed to doInitBody(); then the body of the tag will be evaluated, and during that evaluation out will be bound to the BodyContent just passed to the BodyTag handler. Then doAfterBody() will be evaluated. If that method returns SKIP_BODY, no more evaluations of the body will be done; if the method returns EVAL_BODY_AGAIN, then the body will be evaluated, and doAfterBody() will be invoked again.

The content of a BodyContent instance remains available until after the invocation of its associated doEndTag() method.

A common use of the BodyContent is to extract its contents into a String and then use the String as a value for some operation. Another common use is to take its contents and push it into the out Stream that was valid when the start tag was encountered (that is available from the PageContext object passed to the handler in setPageContext).

3. Dynamic Attributes

Any tag handler can optionally extend the DynamicAttributes interface to indicate that it supports dynamic attributes. In addition to implementing the DynamicAttributes interface, tag handlers that support dynamic attributes must declare that they do so in the Tag Library Descriptor.

The TLD is what ultimately determines whether a tag handler accepts dynamic attributes or not. If a tag handler declares that it supports dynamic attributes in the TLD but it does not implement the DynamicAttributes interface, the tag handler must be considered invalid by the container.

If the dynamic-attributes element for a tag being invoked contains the value "true", the following requirements apply:

  • For each attribute specified in the tag invocation that does not have a corresponding attribute element in the TLD for this tag, a call must be made to setDynamicAttribute(), passing in the namespace of the attribute (or null if the attribute does not have a namespace or prefix), the name of the attribute without the namespace prefix, and the final value of the attribute.
  • Dynamic attributes must be considered to accept request-time expression values as well as deferred expressions.
  • Dynamic attributes must be treated as though they were of type java.lang.Object. If a ValueExpression is passed as a dynamic attribute, the default value for the expected return type is assumed to be java.lang.Object. If a MethodExpression is passed as a dynamic attribute, the default method signature is assumed to be void method().
  • Note that passing a String literal as a dynamic attribute will never be considered as a deferred expression.
  • The JSP container must recognize dynamic attributes that are passed to the tag handler using the <jsp:attribute> standard action.
  • If the setDynamicAttribute() method throws JspException, the doStartTag() or doTag() method is not invoked for this tag, and the exception must be treated in the same manner as if it came from a regular attribute setter method.
  • For a JSP document in either standard or XML syntax, If a dynamic attribute has a prefix that doesn't map to a namespace, a translation error must occur. In standard syntax, only namespaces defined using taglib directives are recognized.

In the following example, assume attributes a and b are declared using the attribute element in the TLD, attributes d1 and d2 are not declared, and the dynamic-attributes element is set to "true". The attributes are set using the calls:

  • setA( "1" ),
  • setDynamicAttribute( null, "d1", "2" ),
  • setDynamicAttribute( "http://www.foo.com/jsp/taglib/mytag.tld", "d2", "3" ),
  • setB( "4" ),
  • setDynamicAttribute( null, "d3", "5" ), and
  • setDynamicAttribute( "http://www.foo.com/jsp/taglib/mytag.tld", "d4", "6" ).
<jsp:root xmlns:mytag="http://www.foo.com/jsp/taglib/mytag.tld" version="2.0">
  <mytag:invokeDynamic a="1" d1="2" mytag:d2="3">
    <jsp:attribute name="b">4</jsp:attribute>
    <jsp:attribute name="d3">5</jsp:attribute>
    <jsp:attribute name="mytag:d4">6</jsp:attribute>
  </mytag:invokeDynamic>
</jsp:root>

4. Annotated Tag Handler Management Example

Below is a somewhat complete example of the way one JSP container could choose to do some tag handler management. There are many other strategies that could be followed, with different pay offs.

In this example, we are assuming that x:iterate is an iterative tag, while x:doit and x:foobar are simple tag. We will also assume that x:iterate and x:foobar implement the TryCatchFinally interface, while x:doit does not.

<x:iterate src="foo">
  <x:doit att1="one" att2="<%= 1 + 1 %>" />
  <x:foobar />
  <x:doit att1="one" att2="<%= 2 + 2 %>" />
</x:iterate>
<x:doit att1="one" att2="<%= 3 + 3 %>" />

The particular code shown below assumes there is some pool of tag handlers that are managed (details not described, although pool managing is simpler when there are no optional attributes), and attemps to reuse tag handlers if possible. The code also "hoists" setting of properties to reduce the cost when appropriate, e.g. inside an iteration.


boolean b1, b2;
IterationTag i; // for x:iterate
Tag d; // for x:doit
Tag d; // for x:foobar

page: // label to end of page...


// initialize iteration tag
i = get tag from pool or new();

i.setPageContext(pc);
i.setParent(null);
i.setSrc("foo");

// x:iterate implements TryCatchFinally
try {
    if ((b1 = i.doStartTag()) == EVAL_BODY_INCLUDE) {

        // initialize doit tag
        // code has been moved out of the loop for show
        d = get tag from pool or new();

        d.setPageContext(pc);
        d.setParent(i);
        d.setAtt1("one");

    loop:
        while (1) do {
            // I'm ignoring newlines...

            // two invocations, fused together

            // first invocation of x:doit
            d.setAtt2(1+1);
            if ((b2 = d.doStartTag()) == EVAL_BODY_INCLUDE) {
                // nothing
            } else if (b2 != SKIP_BODY) {
                // Q? protocol error ...
            }
            if ((b2 = d.doEndTag()) == SKIP_PAGE) {
                break page;  // be done with it.
            } else if (b2 != EVAL_PAGE) {
                // Q? protocol error
            }

	    // x:foobar invocation
            f = get tag from pool or new();
            f.setPageContext(pc);
            f.setParent(i);

            // x:foobar implements TryCatchFinally
            try {
        
                if ((b2 = f.doStartTag()) == EVAL_BODY_INCLUDE) {
                    // nothing
                } else if (b2 != SKIP_BODY) {
                    // Q? protocol error
                }
                if ((b2 = f.doEndTag()) == SKIP_PAGE) {
                    break page;  // be done with it.
                } else if (b2 != EVAL_PAGE) {
                    // Q? protocol error
                }
            } catch (Throwable t) {
                f.doCatch(t); // caught, may been rethrown!
            } finally {
                f.doFinally();
            }

            // put f back to pool
        
            // second invocation of x:doit
            d.setAtt2(2+2);
            if ((b2 = d.doStartTag()) == EVAL_BODY_INCLUDE) {
                // nothing
            } else if (b2 != SKIP_BODY) {
                // Q? protocol error
            }
            if ((b2 = d.doEndTag()) == SKIP_PAGE) {
                break page;  // be done with it.
            } else if (b2 != EVAL_PAGE) {
                // Q? protocol error
            }

            if ((b2 = i.doAfterBody()) == EVAL_BODY_AGAIN) {
                break loop;
            } else if (b2 != SKIP_BODY) {
                // Q? protocol error
            }
        // loop
        }

    } else if (b1 != SKIP_BODY) {
        // Q? protocol error
    }

    // tail end of the IteratorTag ...

    if ((b1 = i.doEndTag()) == SKIP_PAGE) {
        break page;   // be done with it.
    } else if (b1 != EVAL_PAGE) {
        // Q? protocol error
    }
    
    // third invocation
    // this tag handler could be reused from the previous ones.
    d = get tag from pool or new();

    d.setPageContext(pc);
    d.setParent(null);
    d.setAtt1("one");
    d.setAtt2(3+3);

    if ((b1 = d.doStartTag()) == EVAL_BODY_INCLUDE) {
        // nothing
    } else if (b1 != SKIP_BODY) {
        // Q? protocol error
    }
    if ((b1 = d.doEndTag()) == SKIP_PAGE) {
        break page;  // be done with it.
    } else if (b1 != EVAL_PAGE) {
        // Q? protocol error
    }

} catch (Throwable t) {
    i.doCatch(t); // caught, may been rethrown!
} finally {
    i.doFinally();
}

5. Cooperating Actions

Actions can cooperate with other actions and with scripting code in a number of ways.

PageContext

Often two actions in a JSP page will want to cooperate, perhaps by one action creating some server-side object that needs to be accessed by another. One mechanism for doing this is by giving the object a name within the JSP page; the first action will create the object and associate the name to it while the second action will use the name to retrieve the object.

For example, in the following JSP segment the foo action might create a server-side object and give it the name "myObject". Then the bar action might access that server-side object and take some action.

<x:foo id="myObject" />
<x:bar ref="myObjet" />

In a JSP implementation, the mapping "name"->value is kept by the implicit object pageContext. This object is passed around through the Tag handler instances so it can be used to communicate information: all it is needed is to know the name under which the information is stored into the pageContext.

The Runtime Stack

An alternative to explicit communication of information through a named object is implicit coordination based on syntactic scoping.

For example, in the following JSP segment the foo action might create a server-side object; later the nested bar action might access that server-side object. The object is not named within the pageContext: it is found because the specific foo element is the closest enclosing instance of a known element type.

<foo>
   <bar/>
</foo>

This functionality is supported through the TagSupport.findAncestorWithClass(Tag, Class), which uses a reference to parent tag kept by each Tag instance, which effectively provides a run-time execution stack.

6. Simple Tag Handlers

This section presents the API to implement Simple Tag Handlers. Simple Tag Handlers present a much simpler invocation protocol than do Classic Tag Handlers.

The Tag Library Descriptor maps tag library declarations to their physical underlying implementations. A Simple Tag Handler is represented in Java by a class which implements the SimpleTag interface.

Unlike classic tag handlers, the SimpleTag interface does not extend Tag. Instead of supporting doStartTag() and doEndTag(), the SimpleTag interface provides a simple doTag() method, which is called once and only once for any given tag invocation. All tag logic, iteration, body evaluations, etc. are to be performed in this single method. Thus, simple tag handlers have the equivalent power of BodyTag, but with a much simpler lifecycle and interface.

To support body content, the setJspBody() method is provided. The container invokes the setJspBody() method with a JspFragment object encapsulating the body of the tag. The tag handler implementation can call invoke() on that fragment to evaluate the body. The SimpleTagSupport convenience class provides getJspBody() and other useful methods to make this even easier.

Lifecycle of Simple Tag Handlers

This section describes the lifecycle of simple tag handlers, from creation to invocation. For all semantics left unspecified by this section, the semantics default to that of a classic tag handler.

When a simple tag handler is invoked, the following steps occur (in order):

  1. Simple tag handlers are created initially using a zero argument constructor on the corresponding implementation class. Unlike classic tag handlers, this instance must never be pooled by the container. A new instance must be created for each tag invocation.
  2. The setJspContext() and setParent() methods are invoked on the tag handler. The setParent() method need not be called if the value being passed in is null. In the case of tag files, a JspContext wrapper is created so that the tag file can appear to have its own page scope. Calling getJspContext() must return the wrapped JspContext.
  3. The attributes specified as XML element attributes (if any) are evaluated next, in the order in which they are declared, according to the following rules (referred to as "evaluating an XML element attribute" below). The appropriate bean property setter is invoked for each. If no setter is defined for the specified attribute but the tag accepts dynamic attributes, the setDynamicAttribute() method is invoked as the setter.
    • If the attribute is a scripting expression (e.g. "<%= 1+1 %>" in JSP syntax, or "%= 1+1 %" in XML syntax), the expression is evaluated, and the result is converted as per the rules in "Type Conversions", and passed to the setter.
    • Otherwise, if the attribute contains any Expression Language expressions (e.g. "Hello ${name}"), the expression is evaluated, and the result is converted and passed to the setter.
    • Otherwise, the attribute value is taken verbatim, converted, and passed to the setter.
  4. The value for each <jsp:attribute> element is evaluated, and the corresponding bean property setter methods are invoked for each, in the order in which they appear in the body of the tag. If no setter is defined for the specified attribute but the tag accepts dynamic attributes, the setDynamicAttribute() method is invoked as the setter.
    • Otherwise, if the attribute is not of type JspFragment, the container evaluates the body of the <jsp:attribute> element. This evaluation can be done in a container-specific manner. Container implementors should note that in the process of evaluating this body, other custom actions may be invoked.
    • Otherwise, if the attribute is of type JspFragment, an instance of a JspFragment object is created and passed in.
  5. The value for the body of the tag is determined, and if a body exists the setJspBody() method is called on the tag handler.
    • If the tag is declared to have a body-content of "empty" or no body or an empty body is passed for this invocation, then setJspBody() is not called.
    • Otherwise, the body of the tag is either the body of the <jsp:body> element, or the body of the custom action invocation if no <jsp:body> or <jsp:attribute> elements are present. In this case, an instance of a JspFragment object is created as per the lifecycle described in the JSP Fragments section and it is passed to the setter. If the tag is declared to have a body-content of "tagdependent" the JspFragment must echo the body's contents verbatim. Otherwise, if the tag is declared to have a body-content of type "scriptless", the JspFragment must evaluate the body's contents as a JSP scriptless body.
  6. The doTag() method is invoked.
  7. The implementation of doTag() performs its function, potentially calling other tag handlers (if the tag handler is implemented as a tag file) and invoking fragments.
  8. The doTag() method returns, and the tag handler instance is discarded. If SkipPageException is thrown, the rest of the page is not evaluated and the request is completed. If this request was forwarded or included from another page (or Servlet), only the current page evaluation stops.
  9. For each tag scripting variable declared with scopes AT_BEGIN or AT_END, the appropriate scripting variables and scoped attributes are declared, as with classic tag handlers.

7. JSP Fragments

JSP Fragments are represented in Java by an instance of the javax.servlet.jsp.tagext.JspFragment abstract class. Pieces of JSP code are translated into JSP fragments in the context of a tag invocation. JSP Fragments are created when providing the body of a <jsp:attribute> standard action for an attribute that is defined as a fragment or of type JspFragment, or when providing the body of a tag invocation handled by a Simple Tag Handler.

Before being passed to a tag handler, the JspFragment instance is associated with the JspContext of the surrounding page in an implementation-dependent manner. In addition, it is associated with the parent Tag or SimpleTag instance for collaboration purposes, so that when a custom action is invoked from within the fragment, setParent() can be called with the appropriate value. The fragment implementation must keep these associations for the duration of the tag invocation in which it is used.

The invoke() method executes the body and directs all output to either the passed in java.io.Writer or the JspWriter returned by the getOut() method of the JspContext associated with the fragment.

The implementation of each method can optionally throw a JspException, which must be handled by the invoker. Note that tag library developers and page authors should not generate JspFragment implementations manually.

The following sections specify the creation and invocation lifecycles of a JSP Fragment in detail, from the JSP Container's perspective.

Creation of a JSP Fragment

When a JSP fragment is created, the following steps occur (in order):

  1. An instance of a class implementing the JspFragment abstract class is obtained (may either be created or can optionally be cached) each time the tag is invoked. This instance must be configured to produce the contents of the body of the fragment when invoked. If the fragment is defining the body of a <jsp:attribute>, the fragment must evaluate the body each time it is invoked. Otherwise, if the fragment is defining the body of a simple tag, the behavior of the fragment when invoked varies depending on the body-content declared for the tag:
    • If the body-content is "tagdependent", then the fragment must echo the contents of the body verbatim when invoked.
    • If the body-content is "scriptless", then the fragment must evaluate the body each time it is invoked.
  2. The JspFragment instance is passed a reference to the current JspContext. Whenever the fragment invokes a tag handler, it must use this value when calling setJspContext().
  3. The JspFragment instance is associated with an instance of the tag handler of the nearest enclosing tag invocation, or with null if there is no enclosing tag. Whenever the fragment invokes a tag handler, the fragment must use this value when calling setParent().

Invocation of a JSP Fragment

After a JSP fragment is created, it is passed to a tag handler for later invocation. JSP fragments can be invoked either programmatically from a tag handler written in Java, or from a tag file using the <jsp:invoke> or <jsp:doBody> standard action.

JSP fragments are passed to tag handlers using a bean property of type JspFragment. These fragments can be invoked by calling the invoke() method in the JspFragment abstract class. Note that it is legal (and possible) for a fragment to recursively invoke itself, indirectly.

The following steps are followed when invoking a JSP fragment:

  1. The tag handler invoking the fragment is responsible for setting the values of all declared AT_BEGIN and NESTED variables in the JspContext of the calling page/tag, before invoking the fragment. Note that this is not always the same as the JspContext of the fragment being invoked, as fragments can be passed from one tag to another. In the case of tag files, for each variable declared in scope AT_BEGIN or NESTED, if a page scoped attribute exists with the provided name in the tag file, the JSP container must generate code to create/update the page scoped attribute of the provided name in the calling page/tag. If a page scoped attribute with the provided name does not exist in the calling page, and a page scoped attribute of the provided name is present in the tag file, the scoped attribute is removed from the tag file's page scope. See the chapter on Tag Files for details.
  2. If <jsp:invoke> or <jsp:doBody> is being used to invoke a fragment, if the var attribute is specified, a custom java.io.Writer is created that can expose the result of the invocation as a java.lang.String object. If the varReader attribute is specified, a custom java.io.Writer object is created that can expose the resulting invocation as a java.io.Reader object.
  3. The invoke() method of the fragment is invoked, passing in an optional Writer.
  4. Before executing the body of the fragment, if a non-null value is provided for the writer parameter, then the value of JspContext.getOut() and the implicit "out" object must be updated to send output to that writer. To accomplish this, the container must call pushBody( writer ) on the current JspContext, where writer is the instance of java.io.Writer passed to the fragment upon invocation.
  5. The body of the fragment is then evaluated by executing the generated code. The body of the fragment may execute other standard or custom actions. If a classic Custom Tag Handler is invoked and returns SKIP_PAGE, or if a Simple Tag Handler is invoked and throws SkipPageException, the JspFragment must throw SkipPageException to signal that the calling page is to be skipped.
  6. Once the fragment has completed its evaluation, even if an exception is thrown, the value of JspContext.getOut() must be restored via a call to popBody() on the current JspContext.
  7. The fragment returns from invoke()
  8. If <jsp:invoke> or <jsp:doBody> is being used to invoke a fragment, if the var or varReader attribute is specified, a scoped variable with a name equal to the value of the var or varReader attribute is created (or modified) in the page scope, and the value is set to a java.lang.String or java.io.Reader respectively that can produce the results of the fragment invocation.
  9. The invoke() method can be called again, zero or more times. When the tag invocation defining the fragment is complete, the tag must discard the fragment instance since it might be reused by the container.

8. Example Simple Tag Handler Scenario

The following non-normative example is intended to help solidify some of the concepts relating to Tag Files, JSP Fragments and Simple Tag Handlers. In the first section, two sample input files are presented, a JSP (my.jsp), and a simple tag handler implemented using a tag file (simpletag.tag). One possible output of the translation process is presented in the second section.

Although short, the example shows all concepts, including the variable directive. In practice most uses of tags will be much simpler, but probably longer.

The sample generated code is annotated with comments that point to lifecycle steps presented in various sections. The notation is as follows:

  • "Step T.x" = Annotated step x from "Lifecycle of Simple Tag Handlers" earlier in this Chapter.
  • "Step C.x" = Annotated step x from "Creation of a JSP Fragment" earlier in this Chapter.
  • "Step F.x" = Annotated step x from "Invocation of a JSP Fragment" earlier in this Chapter.

Sample Source Files

This section presents the sample source files in this scenario, from which the output files are generated.

Original JSP (my.jsp)

<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>

<my:simpleTag x="10">
    <jsp:attribute name="y">20</jsp:attribute>
    <jsp:attribute name="nonfragment">
        Nonfragment Template Text
    </jsp:attribute>
    <jsp:attribute name="frag">
        Fragment Template Text ${var1}
    </jsp:attribute>
    <jsp:body>
        Body of tag that defines an AT_BEGIN
        scripting variable ${var1}.
    </jsp:body>
</my:simpleTag>

Original Tag File (/WEB-INF/tags/simpletag.tag)

<%-- /WEB-INF/tags/simpletag.tag --%>
<%@ attribute name="x" %>
<%@ attribute name="y" %>
<%@ attribute name="nonfragment" %>
<%@ attribute name="frag" fragment="true" %>
<%@ variable name-given="var1" scope="AT_BEGIN" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Some template text.
<c:set var="var1" value="${x+y}"/>
<jsp:invoke fragment="frag" varReader="var1"/>

Invoke the body:
<jsp:doBody/>

Sample Generated Files

This section presents sample output files that might be generated by a JSP compiler, from the source files presented in the previous section.

Helper class for JspFragment (JspFragmentBase.java)

public abstract class JspFragmentBase
    implements javax.servlet.jsp.tagext.JspFragment
{
    protected javax.servlet.jsp.JspContext jspContext;
    protected javax.servlet.jsp.tagext.JspTag parentTag;
    public void JspFragmentBase(
        javax.servlet.jsp.JspContext jspContext,
        javax.servlet.jsp.tagext.JspTag parentTag )
    {
        this.jspContext = jspContext;
        this.parentTag = parentTag;
    }
}

Relevant Portion of JSP Service Method

// Step T.1 - Initial creation
MySimpleTag _jsp_mySimpleTag = new MySimpleTag();
// Step T.2 - Set page context and parent (since parent is null,
// no need to call setParent() in this case)
_jsp_mySimpleTag.setJspContext( jspContext );
// Step T.3 - XML element attributes evaluated and set
_jsp.mySimpleTag.setX( "10" );
// Step T.4 - <jsp:attribute> elements evaluated and set
//   - parameter y
// (using PageContext.pushBody() is one possible implementation - 
// one limitation is that this code will only work for Servlet-based code).
out = ((PageContext)jspContext).pushBody();
out.write( "20" );
_jsp_mySimpleTag.setY( 
    ((javax.servlet.jsp.tagext.BodyContent)out).getString() );
out = jspContext.popBody();
//   - parameter nonfragment
// (using PageContext.pushBody() is one possible implementation - 
// one limitation is that this code will only work for Servlet-based code).
// Note that trim is enabled by default, else we would have "\n    Non..."
out = ((PageContext)jspContext).pushBody();
out.write( "Nonfragment Template Text" );
_jsp_mySimpleTag.setNonfragment( 
    ((javax.servlet.jsp.tagext.BodyContent)out).getString() );
out = jspContext.popBody();
//   - parameter frag
_jsp_mySimpleTag.setFrag(
    // Step C.1 - New instance of fragment created
    // Step C.2 - Store jspContext
    // Step C.3 - Association with nearest enclosing Tag instance
    new JspFragmentBase( jspContext, _jsp_mySimpleTag ) {
        public void invoke( java.io.Writer writer ) {
	    javax.servlet.jsp.JspWriter out;
            // Step F.1-F.3 done in tag file (see following example)
	    // Step F.4 - If writer provided, push body:
	    if( out == null ) {
		out = this.jspContext.getOut();
	    }
	    else {
		out = this.jspContext.pushBody( writer );
	    }
	    // Step F.5 - Evaluate body of fragment:
            try {
                out.write( "Fragment Template Text " );
                out.write( jspContext.getExpressionEvaluator().evaluate(
		    "${var1}",
		    java.lang.String.class,
		    vResolver, fMapper, "my" ) );
            }
            finally {
                // Step F.6 - Restore value of JspContext.getOut()
		if( writer != null ) {
		    this.jspContext.popBody();
		}
            }

            // Step F.7-F.9 done in tag file (see following example)
        }
    } );
// Step T.5 - Determine and set body of the tag
// - body of tag
_jsp_mySimpleTag.setJspBody(
    // Step C.1 - New instance of fragment created
    // Step C.2 - Store jspContext
    // Step C.3 - Association with nearest enclosing Tag instance
    new JspFragmentBase( jspContext, _jsp_mySimpleTag ) {
        public void invoke( java.io.Writer writer ) {
	    javax.servlet.jsp.JspWriter out;
            // Step F.1-F.3 done in tag file (see following example)
	    // Step F.4 - If writer provided, push body:
	    if( writer == null ) {
		out = this.jspContext.getOut();
	    }
	    else {
		out = this.jspContext.pushBody( writer );
	    }
	    // Step F.5 - Evaluate body of fragment:
            try {
                out.write(
                    "Body of tag that defines an AT_BEGIN\n" +
                    " scripting variable " );
                out.write( jspContext.getExpressionEvaluator().evaluate(
		    "${var1}",
		    java.lang.String.class,
		    vResolver, fMapper, "my" ) );
                out.write( ".\n" );
            }
            finally {
                // Step F.6 - Restore value of JspContext.getOut()
		if( writer != null ) {
		    this.jspContext.popBody();
		}
            }

            // Step F.7-F.9 done in tag file (see following example)
        }
    } );
// Step T.6 - Inovke doTag
// Step T.7 occurs in the tag file (see following example)
// Step T.8 - doTag returns - page will catch SkipPageException.
_jsp_mySimpleTag.doTag();
// Step T.9 - Declare AT_BEGIN and AT_END scripting variables
String var1 = (String)jspContext.findAttribute( "var1" );

Generated Simple Tag Handler (MySimpleTag.java)

public class MySimpleTag
    extends javax.servlet.jsp.tagext.SimpleTagSupport
{
    // Attributes:
    private String x;
    private String y;
    private String nonfragment;
    private javax.servlet.jsp.tagext.JspFragment frag;
    // Setters and getters for attributes:
    public void setX( Stirng x ) {
        this.x = x; 
    }
    public String getX() {
        return this.x; 
    }
    public void setY( String y ) { 
        this.y = y; 
    }
    public String getY() { 
        return this.y; 
    }
    public void setNonfragment( String nonfragment ) {
        this.nonfragment = nonfragment; 
    }
    public String getNonfragment() {
        return this.nonfragment;
    }
    public void setFrag( javax.servlet.jsp.tagext.JspFragment frag ) {
        this.frag = frag;
    }
    public javax.servlet.jsp.tagext.JspFragment getFrag() {
        return this.frag;
    }

    protected JspContext jspContext;
    public void setJspContext( JspContext ctx ) {
	super.setJspContext( ctx );
	// Step T.2 - A JspContext wrapper is created.
	// (Implementation of wrapper not shown).
	this.jspContext = new utils.JspContextWrapper( ctx );
    }
    public JspContext getJspContext() {
	// Step T.2 - Calling getJspContext() must return the 
	// wrapped JspContext.
	return this.jspContext;
    }

    public void doTag() throws JspException {
	java.lang.Object jspValue;
	JspContext jspContext = getJspContext();
	JspContext _jsp_parentContext = 
	    SimpleTagSupport.this.getJspContext();
	try {
	    javax.servlet.jsp.JspWriter out = jspContext.getOut();

	    // Create page-scope attributes for each tag attribute:
	    this.jspContext.setAttribute( "x", getX() );
	    this.jspContext.setAttribute( "y", getY() );
	    this.jspContext.setAttribute( "nonfragment", getNonfragment() );
	    this.jspContext.setAttribute( "frag", getFrag() );

	    // Synchronize AT_BEGIN variables from calling page
	    if( (jspValue = _jsp_parentContext.getAttribute( 
		    "var1" )) != null ) 
	    {
		jspContext.setAttribute( "var1", value );
	    }
	    else {
		jspContext.removeAttribute( "var1", 
		    JspContext.PAGE_SCOPE );
	    }

	    // Tag template text:
	    out.write( "\n\n\n\n\n\n\n\nSome template text.\n" );

	    // Invoke c:set - recognized tag handler from JSTL:
	    jspContext.setAttribute( "var1", 
		jspContext.getExpressionEvaluator().evaluate(
		    "${x+y}",
		    java.lang.String.class,
		    jspContext,
		    prefixMap, functionMap, "my" ) );

	    // Invoke the "frag" fragment:
	    // Step F.1 - Set values of AT_BEGIN and NESTED variables
	    //     in calling page context.
	    if( (jspValue = jspContext.getAttribute( "var1" )) != null ) {
		_jsp_parentContext.setAttribute( "var1", value );
	    }
	    else {
		_jsp_parentContext.removeAttribute( "var1", 
		    JspContext.PAGE_SCOPE );
	    }

	    // Step F.2 - varReader is specified, generate a writer.
	    java.io.Writer _jsp_sout = new java.io.StringWriter();

	    // Step F.3 - Invoke fragment with writer
	    getFrag().invoke( _jsp_sout );

	    // Step F.4 - F.6 occur in the fragment (see above)
	    // Step F.7 - fragment returns

	    // Step F.8 - varReader specified, so save to var
	    jspContext.setAttribute(
		"var1", new StringReader( _jsp_sout.toString() ) );

	    // Step F.9 - Done!


	    out.write( "\n\nInvoke the body:\n" );

	    // Invoke the body of the tag:
	    // Step F.1 - Set values of AT_BEGIN and NESTED variables
	    //     in calling page context.
	    if( (jspValue = jspContext.getAttribute( "var1" )) != null ) {
		_jsp_parentContext.setAttribute( "var1", value );
	    }
	    else {
		_jsp_parentContext.removeAttribute( "var1", 
		    JspContext.PAGE_SCOPE);
	    }

	    // Step F.2 - varReader is not specified - does not apply.

	    try {
		// Step F.3 - Invoke body, passing optional writer
		getJspBody().invoke( null );
	    }
	    finally {
		// Steps F.4 - F.6 occur in the fragment (see above)
		// Step F.7 - fragment returns
	    }

	    // Step F.8 does not apply.
	    // Step F.9 - Done!
	}
	finally {
	    // Tag handlers generate code to synchronize AT_BEGIN with
	    // calling page, regardless of whether an error occurs.
	    if( (jspValue = jspContext.getAttribute( "var1" )) != null ) {
		_jsp_parentContext.setAttribute( "var1", value );
	    }
	    else {
		_jsp_parentContext.removeAttribute( "var1", 
		    JspContext.PAGE_SCOPE );
	    }
	}
    }
}

9. Translation-time Classes

The following classes are used at translation time.

Tag mapping, Tag name

A taglib directive introduces a tag library and associates a prefix to it. The TLD associated with the library associates Tag handler classes (plus other information) with tag names. This information is used to associate a Tag class, a prefix, and a name with each custom action element appearing in a JSP page.

At execution time the implementation of a JSP page will use an available Tag instance with the appropriate property settings and then follow the protocol described by the interfaces Tag, IterationTag, BodyTag, SimpleTag, and TryCatchFinally. The implementation guarantees that all tag handler instances are initialized and all are released, but the implementation can assume that previous settings are preserved by a tag handler, to reduce run-time costs.

Scripting Variables

JSP supports scripting variables that can be declared within a scriptlet and can be used in another. JSP actions also can be used to define scripting variables so they can used in scripting elements, or in other actions. This is very useful in some cases; for example, the jsp:useBean standard action may define an object which can later be used through a scripting variable.

In some cases the information on scripting variables can be described directly into the TLD using elements. A special case is typical interpretation of the "id" attribute. In other cases the logic that decides whether an action instance will define a scripting variable may be quite complex and the name of a TagExtraInfo class is instead given in the TLD. The getVariableInfo method of this class is used at translation time to obtain information on each variable that will be created at request time when this action is executed. The method is passed a TagData instance that contains the translation-time attribute values.

Validation

The TLD file contains several pieces of information that is used to do syntactic validation at translation-time. It also contains two extensible validation mechanisms: a TagLibraryValidator class can be used to validate a complete JSP page, and a TagExtraInfo class can be used to validate a specific action. In some cases, additional request-time validation will be done dynamically within the methods in the Tag instance. If an error is discovered, an instance of JspTagException can be thrown. If uncaught, this object will invoke the errorpage mechanism of JSP.

The TagLibraryValidator is an addition to the JSP 1.2 specification and is very open ended, being strictly more powerful than the TagExtraInfo mechanism. A JSP page is presented via the PageData object, which abstracts the XML view of the JSP page.

A PageData instance will provides an InputStream (read-only) on the page. Later specifications may add other views on the page (DOM, SAX, JDOM are all candidates), for now these views can be generated from the InputStream and perhaps can be cached for improved performance (recall the view of the page is just read-only).

As of JSP 2.0, the JSP container must support a jsp:id attribute to provide higher quality validation errors. The container will track the JSP pages as passed to the container, and will assign to each element a unique "id", which is passed as the value of the jsp:id attribute. Each XML element in the XML view will be extended with this attribute. The TagLibraryValidator can use the attribute in one or more ValidationMessage objects. The container then, in turn, can use these values to provide more precise information on the location of an error.

The prefix for the id attribute need not be "jsp" but it must map to the namespace http://java.sun.com/JSP/Page. In the case where the user has redefined the jsp prefix, an alternative prefix must be used by the container.

Validation Details

In detail, validation is done as follows:

First, the JSP page is parsed using the information in the TLD. At this stage valid mandatory and optional attributes are checked.

Second, for each unique tag library in the page as determined by the tag library URI, and in the lexical order in which they appear, their associated validator class (if any) is invoked. This involves several substeps.

The first substep is to obtain an initialized validator instance by either:

  • construct a new instance and invoke setInitParameters() on it, or
  • obtain an existing instance that is not being used, invoke release() on it, and then invoke setInitParameters() on it, or
  • locate an existing instance that is not being used on which the desired setInitParameters() has already been invoked

The class name is as indicated in the <validator-class> element, and the Map passed through setInitParameters() is as described in the <init-params> element. All TagLibraryValidator classes are supposed to keep their initParameters until new ones are set, or until release() is invoked on them.

The second substep is to perform the actual validation. This is done by invoking the validate() method with a prefix, uri, and PageData that correspond to the taglib directive instance being validated and the PageData representing the page. In the case where a single URI is mapped to more than one prefix, the prefix of the first URI must be used.

The last substep is to invoke the release() method on the validator tag when it is no longer needed. This method releases all resources.

Finally, after checking all the tag library validator classes, the TagExtraInfo classes for all tags will be consulted by invoking their validate method. The order of invocation of this methods is undefined.

www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.