JSP.6.1 Package javax.servlet.jsp


JSP.6.1 Package javax.servlet.jsp

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.6.1.1 JspPage and HttpJspPage

Two interfaces describe the interaction between a class implementing a JSP page and the JSP container: HttpJspPage and JspPage . Chapter JSP.3 describes the role of these two interfaces in detail. The JspPage contract is not described further here; see the javadoc documentation for details.

The large majority of the JSP pages use the HTTP protocol and thus are based on the HttpJspPage contract. This interface has three methods , two of which can be redefined by the JSP author using a declaration scripting element:

jspInit()

The jspInit() method is invoked when the JSP page is initialized . It is the responsibility of the JSP implementation (and of the class mentioned by the extends attribute, if present) that at this point invocations to the getServletConfig() method will return the desired value.

A JSP page can override this method by including a definition for it in a declaration element.

The signature of this method is void jspInit() .

jspDestroy()

The jspDestroy() method is invoked when the JSP page is about to be destroyed .

A JSP page can override this method by including a definition for it in a declaration element.

The signature of this method is void jspDestroy() .

_jspService()

The _jspService() method corresponds to the body of the JSP page. This method is defined automatically by the JSP container and should never be defined by the JSP page author.

If a superclass is specified using the extends attribute, that superclass may choose to perform some actions in its service() method before or after calling the _jspService() method. See Section JSP.3.2.4.

The signature of this method is public void _jspService(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException.

JSP.6.1.2 JspWriter

The actions and template data in a JSP page is written using the JspWriter object that is referenced by the implicit variable out . This variable is initialized by code generated automatically by the JSP container (see the PageContext object in Section JSP.6.1.4).

The initial JspWriter object is associated with the PrintWriter object of the ServletResponse in a way that depends on whether the page is or is not buffered. If the page is not buffered, output written to this JspWriter object will be written through to the PrintWriter directly, which will be created if necessary by invoking the getWriter() method on the response object. But if the page is buffered, the PrintWriter object will not be created until when the buffer is flushed, and operations like setContentType() are legal. Since this flexibility simplifies programming substantially, buffering is the default for JSP pages.

Buffering raises the issue of what to do when the buffer is exceeded. Two approaches can be taken:

  • Exceeding the buffer is not a fatal error; when the buffer is exceeded, just flush the output.

  • Exceeding the buffer is a fatal error; when the buffer is exceeded, raise an exception.

Both approaches are valid, and thus both are supported in the JSP technology. The behavior of a page is controlled by the autoFlush attribute, which defaults to true. In general, JSP pages that need to be sure that correct and complete data has been sent to their client may want to set autoFlush to false , with a typical case being that where the client is an application itself. On the other hand, JSP pages that send data that is meaningful even when partially constructed may want to set autoFlush to true ; a case may be when the data is sent for immediate display through a browser. Each application will need to consider its specific needs.

An alternative considered was to make the buffer size unbounded, but this has the disadvantage that runaway computations may consume an unbounded amount of resources.

The JspWriter interface includes behaviors from java.io.BufferedWriter and java.io.PrintWriter APIs but incorporates buffering and does not consume IOExceptions as PrintWriter does. If a particular use requires a PrintWriter , as in the case of desiring to insert an exception stack trace, one can be obtained by wrapping the JspWriter with a PrintWriter .

The usual methods found in PrintWriter are available with the only modification being that the JspWriter methods do not consume IOExceptions . The additional methods are:

clear()

This method is used to clear the buffer of data. It is illegal to invoke it if the JspWriter is not buffered. An exception will be raised if the buffer has been autoFlushed and clear() is invoked. Also see clearBuffer() .

The method signature is void clear() .

clearBuffer()

This method is like clear() except that no exception will be raised if the buffer has been autoFlushed() .

The method signature is void clearBuffer() .

flush()

This method is used to flush the buffer of data. The method may be invoked indirectly if the buffer size is exceeded. The underlying PrintWriter object is guaranteed to be created exactly the first time data is flushed to it.

The method signature is void flush() .

close()

This method can be used to close the stream. It need not be invoked explicitly for the initial JspWriter as the code generated by the JSP container will automatically include a call to close() .

The method signature is void close() .

getBufferSize()

This method returns the size of the buffer used by the JspWriter .

The method signature is int getBufferSize() .

getRemaining()

This method returns the number of unused bytes in the buffer.

The method signature is int getRemaining() .

isAutoFlush()

This method indicates whether the JspWriter is autoFlushing .

The method signature is boolean isAutoFlush() .

JSP.6.1.3 JspException and JspError

JspException is a generic exception class. It currently has one subclass: JspError .

A JspError has a message and it reflects an unexpected error that has been found during the execution of a JSP page. If uncaught, the error will result in an invocation of the error page machinery.

JSP.6.1.4 PageContext

A PageContext provides an object that encapsulates implementation-dependent features and provides convenience methods. A JSP page implementation class that uses a PageContext as shown in Figure JSP.6-1 will run unmodified in any compli-ant JSP container taking advantage of implementation-specific improvements like high performance JspWriters . JSP 1.1 compliant containers must generate JSP page implementation classes that use this PageContext object to provide insulation from platform implementation details.

Figure JSP.6-1 Using PageContext to Provide Implementation Independence
 public void _jspService(HttpServletRequest request,                  HttpServletResponse response)             throws IOException, ServletException {    JSPFactory  factory     = JSPFactory.getDefaultFactory();     // Get the page context object for this page     PageContext pageContext = factory.getPageContext(                             this,                              request,                              response,                              null, // e.g. no errorPageURL,                              false, // e.g. no session                              JspWriter.DEFAULT_BUFFER,                              true // autoflush=true                              );     // Initialize implicit variables for scripting     HttpSession session = pageContext.getSession();     JspWriter   out     = pageContext.getOut();     Object      page    = this;     try {            // body of JSP here ...     } catch (Exception e) {            out.clear();             pageContext.handlePageException(e);     } finally {            out.close();             factory.releasePageContext(pageContext);     }  } 

A PageContext object is initialized by a JSP container implementation early on in the processing of the _jspService() method. The PageContext implementation itself is implementation dependent, and is obtained via a creation method on the JspFactory .

The PageContext provides a number of facilities, including:

  • A single API that manages the operations available over various scope namespaces ( page, request, session, application ) such as setAttribute() , getAttribute() , removeAttribute(), etc.

  • A mechanism for obtaining a platform-dependent implementation of the JspWriter that is assigned to the " out " implicit scripting variable.

  • A number of simple convenience getter APIs for obtaining references to various request-time objects.

  • Mechanisms to forward or include the current request being processed to other components in the application.

JSP.6.1.4.1 Creation

The PageContext class is an abstract class, designed to be extended by conforming JSP container runtime environments to provide implementation-dependent implementations .

An instance of a PageContext is created by a JSP container-specific implementation class at the beginning of its _jspService() method via an implementation-specific default JspFactory , as shown in Figure JSP.6-1:

JSP.6.1.4.2 Usage

The PageContext object provides access to multiple functionality.

Uniform Access to Multiple Scopes

These methods provide uniform access to the diverse scope objects. The implementation must use the underlying servlet machinery corresponding to that scope, so information can be passed back and forth between servlets and JSP pages.

getAttribute()

Access an attribute in the page scope, or null if not found.

getAttribute()

Overload of previous method to access an attribute in a given scope or null if not found.

findAttribute()

Searches for the named attribute in page, request, session (if valid), and application scopes in order and returns the value associated or null.

getAttributeNamesInScope()

Enumerate all the attributes in a given scope.

getAttributesScope()

Get the scope where a given attribute is defined.

removeAttribute()

Remove the object reference associated with the given name , look in all scopes in the scope order.

removeAttribute()

Overload of previous method to remove the object reference associated with the given name in the given scope.

setAttribute()

Register the given name and object in the page scope.

setAttribute()

Overload of previous method to register the given name and object in the given scope.

Access to Implicit Objects

These methods provide convenience access to implicit objects and other objects that can be obtained by different ways.

getOut()

The current value of the out object (a JspWriter ).

getException()

The current value of the exception object (an Exception ).

getPage()

The current value of the page object (a Servlet ).

getRequest()

The current value of the request object (a ServletRequest ).

getResponse()

The current value of the response object (a ServletResponse ).

getSession()

The current value of the session object (an HttpSession ).

getServletConfig()

The ServletConfig instance.

getServletContext()

The ServletContext instance.

Management of Nested Scopes

These methods enable the management of nested JspWriter streams to implement tag extensions. Note that pushBody() returns a BodyContent , while popBody() returns a JspWriter , which will need to be casted into a BodyContent in all but the top level.

pushBody()

Return a new BodyContent object, save the current "out" JspWriter , and update the value of the "out" attribute in the page scope attribute namespace of the PageContext .

popBody()

Return the previous JspWriter "out" saved by the matching pushBody() , and update the value of the "out" attribute in the page scope attribute namespace of the PageContext .

Management of PageContext Object

The following two methods provide management of the PageContext object itself. These methods are not intended to be used by the JSP page author.

initialize()

Initialize a PageContext with the given data.

release()

Release a PageContext object.

Forward and Include

These methods encapsulate forwarding and inclusion.

forward()

This method is used to forward the current ServletRequest and ServletResponse to another component in the application.

The signature of this method is void forward(String relativeUrlPath) throws ServletException, IOException .

include()

This method causes the resource specified to be processed as part of the current ServletRequest and ServletResponse being processed by the calling Thread .

The signature of this method is void include(String relativeUrlPath) throws ServletException, IOException .

handlePageException()

Process an unhandled page level exception by performing a redirect.

The signature of this method is void handlePageException(Exception e) throws ServletException, IOException .

JSP.6.1.5 JspEngineInfo

The JspEngineInfo class provides information on the JSP container implementation. The only method currently available is:

getSpecificationVersion()

Returns a String <deleted> in Dewey decimal format </deleted> describing the highest version of the JSP specification implemented by the JSP container. See the java.lang.Package class in the Java 2 platform for other methods that may appear in this class in future specifications.

JSP.6.1.6 JspFactory

The JspFactory provides a mechanism to instantiate platform-dependent objects in a platform-independent manner. The PageContext class and the JspEngineInfo class are the only implementation-dependent classes that can be created from the factory.

Typically, at initialization time, a JSP container will call the static setDefaultFactory() method in order to register its own factory implementation. JSP page implementation classes will use the getDefaultFactory() method in order to obtain this factory and use it to construct PageContext instances in order to process client requests .

JspFactory objects are not intended to be used by JSP page authors.



Java 2 Platform, Enterprise Edition. Platform and Component Specifications
Java 2 Platform, Enterprise Edition: Platform and Component Specifications
ISBN: 0201704560
EAN: 2147483647
Year: 2000
Pages: 399

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net