Skip to content

Latest commit

 

History

History
948 lines (748 loc) · 30.5 KB

Per-RequestStateInformation.adoc

File metadata and controls

948 lines (748 loc) · 30.5 KB

Per-Request State Information

During request processing for a Jakarta Faces page, a context object is used to represent request-specific information, as well as provide access to services for the application. This chapter describes the classes which encapsulate this contextual information.

FacesContext

Jakarta Faces defines the jakarta.faces.context.FacesContext abstract base class for representing all of the contextual information associated with processing an incoming request, and creating the corresponding response. A FacesContext instance is created by the Jakarta Faces implementation, prior to beginning the request processing lifecycle, by a call to the getFacesContext method of FacesContextFactory, as described in FacesContextFactory. When the request processing lifecycle has been completed, the Jakarta Faces implementation will call the release method, which gives Jakarta Faces implementations the opportunity to release any acquired resources, as well as to pool and recycle FacesContext instances rather than creating new ones for each request.

Application

public Application getApplication();

The Jakarta Faces implementation must ensure that the Application instance for the current web application is available via this method, as a convenient alternative to lookup via an ApplicationFactory.

Attributes

public Map<Object,Object> getAttributes();

Return a mutable Map representing the attributes associated wth this FacesContext instance. This Map is useful to store attributes that you want to go out of scope when the Faces lifecycle for the current request ends, which is not always the same as the request ending, especially in the case of Servlet filters that are invoked after the Faces lifecycle for this request completes. Accessing this Map does not cause any events to fire, as is the case with the other maps: for request, session, and application scope.

ELContext

public ELContext getELContext();

Return the ELContext instance for this FacesContext instance. This ELContext instance has the same lifetime and scope as the FacesContext instance with which it is associated, and may be created lazily the first time this method is called for a given FacesContext instance. Upon creation of the ELContext instance, the implementation must take the following action:

  • Call the ELContext.putContext(java.lang.Class, java.lang.Object) method on the instance, passing in FacesContext.class and the this reference for the FacesContext instance itself.

  • If the Collection returned by jakarta.faces.Application.getELContextListeners() is non-empty, create an instance of ELContextEvent and pass it to each ELContextListener instance in the Collection by calling the ELContextListener.contextCreated(jakarta.el.ELContextEvent) method.

ExternalContext

It is sometimes necessary to interact with APIs provided by the containing environment in which the Jakarta Faces application is running. In most cases this is the servlet API, but it is also possible for a Jakarta Faces application to run inside of a portlet. Jakarta Faces provides the ExternalContext abstract class for this purpose. This class must be implemented along with the FacesContext class, and must be accessible via the getExternalContext method in FacesContext.

public ExternalContext getExternalContext();

The default implementation must return a valid value when this method is called during startup time. See the javadocs for this method for the complete specification.

The ExternalContext instance provides immediate access to all of the components defined by the containing environment (servlet or portlet) within which a Jakarta Faces-based web application is deployed. The following table lists the container objects available from ExternalContext. Note that the Access column refers to whether the returned object is mutable. None of the properties may be set through ExternalContext. itself.

Name Access Type Description

applicationMap

RW

java.util.Map

The application context attributes for this application.

authType

RO

String

The method used to authenticate the currently logged on user (if any).

context

RW

Object

The application context object for this application.

initParameterMap

RO

java.util.Map

The context initialization parameters for this application

remoteUser

RO

String

The login name of the currently logged in user (if any).

request

RW

Object

The request object for this request.

requestContextPath

RO

String

The context path for this application.

requestCookieMap

RO

java.util.Map

The cookies included with this request.

requestHeaderMap

RO

java.util.Map

The HTTP headers included with this request (value is a String).

requestHeaderValuesMap

RO

java.util.Map

.The HTTP headers included with this request (value is a String array).

requestLocale

RW

java.util.Locale

The preferred Locale for this request.

requestLocales

RW

java.util.Iterator

The preferred Locales for this request, in descending order of preference.

requestMap

RW

java.util.Map

The request scope attributes for this request.

requestParameterMap

RO

java.util.Map

The request parameters included in this request (value is a String).

requestParameterNames

RO

Iterator

The set of request parameter names included in this request.

requestParameterValuesMap

RO

java.util.Map

The request parameters included in this request (value is a String array).

requestPathInfo

RO

String

The extra path information from the request URI for this request.

requestServletPath

RO

String

The servlet path information from the request URI for this request.

response

RW

Object

The response object for the current request.

sessionMap

RW

java.util.Map

The session scope attributes for this request [1].

userPrincipal

RO

java.security.Principal

The Principal object containing the name of the currently logged on user (if any).

See the JavaDocs for the normative specification.

Flash

The Flash provides a way to pass temporary objects between the user views generated by the faces lifecycle. Anything one places in the flash will be exposed to the next view encountered by the same user session and then cleared out..

Name Access Type Description

flash

R

Flash

See the javadocs for the complete specification.

ViewRoot

public UIViewRoot getViewRoot();
public void setViewRoot(UIViewRoot root);

During the Restore View phase of the request processing lifecycle, the state management subsystem of the Jakarta Faces implementation will identify the component tree (if any) to be used during the inbound processing phases of the lifecycle, and call setViewRoot() to establish it.

Message Queue

public void addMessage(String clientId, FacesMessage message);

During the Apply Request Values, Process Validations, Update Model Values, and Invoke Application phases of the request processing lifecycle, messages can be queued to either the component tree as a whole (if clientId is null), or related to a specific component based on its client identifier.

public Interator<String> getClientIdsWithMessages();
public Severity getMaximumSeverity();
public Iterator<FacesMessage> getMessages(String clientId);
public Iterator<FacesMessage> getMessages();

The getClientIdsWithMessages() method must return an Iterator over the client identifiers for which at least one Message has been queued. This method must be implemented so the clientIds are returned in the order of calls to addMessage(). The getMaximumSeverity() method returns the highest severity level on any Message that has been queued, regardless of whether or not the message is associated with a specific client identifier or not. The getMessages(String) method returns an Iterator over queued Messages, either those associated with the specified client identifier, or those associated with no client identifier if the parameter is null. The getMessages() method returns an Iterator over all queued Messages, whether or not they are associated with a particular client identifier. Both of the getMessage() variants must be implemented such that the messages are returned in the order in which they were added via calls to addMessage().

For more information about the Message class, see FacesMessage.

RenderKit

public RenderKit getRenderKit();

Return the RenderKit associated with the render kit identifier in the current UIViewRoot (if any).

ResponseStream and ResponseWriter

public ResponseStream getResponseStream();
public void setResponseStream(ResponseStream responseStream);
public ResponseWriter getResponseWriter();
public void setResponseWriter(ResponseWriter responseWriter);
public void enableResponseWriting(boolean enable);

Jakarta Faces supports output that is generated as either a byte stream or a character stream. UIComponents or Renderers that wish to create output in a binary format should call getResponseStream() to acquire a stream capable of binary output. Correspondingly, UIComponents or Renderers that wish to create output in a character format should call getResponseWriter() to acquire a writer capable of character output.

Due to restrictions of the underlying servlet APIs, either binary or character output can be utilized for a particular response—they may not be mixed.

Please see ViewHandler to learn when setResponseWriter() and setResponseStream() are called.

The enableResponseWriting method is useful to enable or disable the writing of content to the current ResponseWriter instance in this FacesContext. If the enable argument is false, content should not be written to the response if an attempt is made to use the current ResponseWriter.

Flow Control Methods

public void renderResponse();
public void responseComplete();
public boolean getRenderResponse();
public boolean getResponseComplete();

Normally, the phases of the request processing lifecycle are executed sequentially, as described in Request Processing Lifecycle. However, it is possible for components, event listeners, and validators to affect this flow by calling one of these methods.

The renderResponse() method signals the Jakarta Faces implementation that, at the end of the current phase (in other words, after all of the processing and event handling normally performed for this phase is completed), control should be transferred immediately to the Render Response phase, bypassing any intervening phases that have not yet been performed. For example, an event listener for a tree control that was designed to process user interface state changes (such as expanding or contracting a node) on the server would typically call this method to cause the current page to be redisplayed, rather than being processed by the application.

The responseComplete() method, on the other hand, signals the Jakarta Faces implementation that the HTTP response for this request has been completed by some means other than rendering the component tree, and that the request processing lifecycle for this request should be terminated when the current phase is complete. For example, an event listener that decided an HTTP redirect was required would perform the appropriate actions on the response object (i.e. calling ExternalContext.redirect()) and then call this method.

In some circumstances, it is possible that both renderResponse() and responseComplete() might have been called for the request. In this case, the Jakarta Faces implementation must respect the responseComplete() call (if it was made) before checking to see if renderResponse() was called.

The getRenderResponse() and getResponseComplete() methods allow a Jakarta Faces-based application to determine whether the renderResponse() or responseComplete() methods, respectively, have been called already for the current request.

Partial Processing Methods

public PartialViewContext getPartialViewContext();

The getPartialViewContext()method must return an instance of PartialViewContext either by creating a new instance, or returning an existing instance from the FacesContext.

Partial View Context

The PartialViewContext contains the constants, properties and methods to facilitate partial view processing and partial view rendering. Refer to Partial View Processing and Partial View Rendering. Refer to the JavaDocs for the jakarta.faces.context.PartialViewContext class for method requirements.

Access To The Current FacesContext Instance

public static FacesContext getCurrentInstance();
protected static void setCurrentInstance(FacesContext context);

Under most circumstances, Jakarta Faces components, and application objects that access them, are passed a reference to the FacesContext instance for the current request. However, in some cases, no such reference is available. The getCurrentInstance() method may be called by any Java class in the current web application to retrieve an instance of the FacesContext for this request. The Jakarta Faces implementation must ensure that this value is set correctly before FacesContextFactory returns a FacesContext instance, and that the value is maintained in a thread-safe manner.

The default implementation must allow this method to be called during application startup time, before any requests have been serviced. If called during application startup time, the instance returned must have the special properties as specified on the javadocs for FacesContext.getCurrentInstance() The .

CurrentPhaseId

The default lifecycle implementation is responsible for setting the currentPhaseId property on the FacesContext instance for this request, as specified in Standard Request Processing Lifecycle Phases. The following table describes this property.

Name Access Type Description

currentPhaseId

RW

PhaseId

The PhaseId constant for the current phase of the request processing lifecycle

ExceptionHandler

The FacesContextFactory ensures that each newly created FacesContext instance is initialized with a fresh instance of ExceptionHandler, created from ExceptionHandlerFactory. The following table describes this property.

Name Access Type Description

exceptionHandler

RW

ExceptionHandler

Set by FacesContextFactory.getFacesContext(), this class is the default exception handler for any unexpected Exceptions that happen during the Faces lifecycle. See the Javadocs for ExceptionHandler for details.

Please see PhaseListener for the circumstances under which ExceptionHandler is used.

ExceptionHandler

ExceptionHandler is the central point for handling unexpected Exceptions that are thrown during the Faces lifecycle. The ExceptionHandler must not be notified of any Exceptions that occur during application startup or shutdown.

Several places in the Faces specification require an Exception to be thrown as a result of normal lifecycle processing. The following expected Exception cases must not be handled by the ExceptionHandler.

  • All cases where a ValidatorException is specified to be thrown or caught

  • All cases where a ConverterException is specified to be thrown or caught

  • The case when a MissingResourceException is thrown during the processing of the <f:loadBundle /> tag.

  • If an exception is thrown when the runtime is processing the @PreDestroy annotation on a managed bean.

  • All classes when an AbortProcessingException is thrown.

All other Exception cases must not be swallowed, and must be allowed to flow up to the Lifecycle.execute() method where the individual lifecycle phases are implemented. At that point, all Exceptions are passed to the ExceptionHandler as described in PhaseListener.

Any code that is not a part of the core Faces implementation may leverage the ExceptionHandler in one of two ways.

Default ExceptionHandler implementation

The default ExceptionHandler must implement the following behavior for each of its methods

public ExceptionQueuedEvent getHandledExceptionEvent();

Return the first “handled” ExceptionQueuedEvent, that is, the one that was actually re-thrown.

public Iterable<ExceptionQueuedEvent> getHandledExceptionEvents();

The default implementation must return an Iterable over all ExceptionEvents that have been handled by the handle() method.

public Throwable getRootCause(Throwable t);

Unwrap the argument t until the unwrapping encounters an Object whose getClass() is not equal to FacesException.class or jakarta.el.ELException.class. If there is no root cause, null is returned.

public Iterable<ExceptionQueuedEvent> getUnhandledExceptionEvents();

Return an Iterable over all ExceptionEvents that have not yet been handled by the handle() method.

public void handle() throws FacesException;

Inspect all unhandled ExceptionQueuedEvent instances in the order in which they were queued by calls to Application.publishEvent(ExceptionQueuedEvent.class, eventContext).

For each ExceptionQueuedEvent in the list, call its getContext() method and call getException() on the returned result. Upon encountering the first such Exception the corresponding ExceptionQueuedEvent must be set so that a subsequent call to getHandledExceptionEvent() or getHandledExceptionEvents() returns that ExceptionQueuedEvent instance. The implementation must also ensure that subsequent calls to getUnhandledExceptionEvents() do not include that ExceptionQueuedEvent instance. Let toRethrow be either the result of calling getRootCause() on the Exception, or the Exception itself, whichever is non-null. Re-wrap toThrow in a ServletException or (PortletException, if in a portlet environment) and throw it, allowing it to be handled by any <error-page> declared in the web application deployment descriptor or by the default error page as described elsewhere in this section.

There are two exceptions to the above processing rules. In both cases, the Exception must be logged and not re-thrown.

  • If an unchecked Exception occurs as a result of calling a method annotated with PreDestroy on a managed bean.

  • If the Exception originates inside the ELContextListener.removeElContextListener() method

The FacesException must be thrown if and only if a problem occurs while performing the algorithm to handle the Exception, not as a means of conveying a handled Exception itself.

public boolean isListenerForSource(Object source);

The default implementation must return true if and only if the source argument is an instance of ExceptionEventContext.

public void processEvent(SystemEvent ExceptionQueuedEvent)
    throws AbortProcessingException;

The default implementation must store the argument ExceptionQueuedEvent in a strongly ordered queue for later processing by the handle() method.

Default Error Page

If no <error-page> elements are declared in the web application deployment descriptor, the runtime must provide a default error page that contains the following information.

  • The stack trace of the Exception

  • The UIComponent tree at the time the ExceptionQueuedEvent was handled.

  • All scoped variables in request, view, session and application scope.

  • If the error happens during the execution of the view declaration language page (VDL)

    • The physical file being traversed at the time the Exception was thrown, such as /user.xhtml

    • The line number within that physical file at the time the Exception was thrown

    • Any available error message(s) from the VDL page, such as: “The prefix "foz" for element "foz:bear" is not bound.”

  • The viewId at the time the ExceptionQueuedEvent was handled

If Application.getProjectStage() returns ProjectStage.Development, the runtime must guarantee that the above debug information is available to be included in any Facelet based error page using the <ui:include /> with a src attribute equal to the string “jakarta.faces.error.xhtml”.

FacesMessage

Each message queued within a FacesContext is an instance of the jakarta.faces.application.FacesMessage class. The presence of one or more FacesMessage instances on the FacesContext indicates a failure of some kind during the lifecycle. In particular, a validation or conversion failure is required to cause a FacesMessage to be added to the FacesContext.

It offers the following constructors:

public FacesMessage();
public FacesMessage(String summary, String detail);
public FacesMessage(Severity severity, String summary, String detail);

The following method signatures are supported to retrieve and set the properties of the completed message:

public String getDetail();
public void setDetail(String detail);

public Severity getSeverity();
public void setSeverity(Severity severity);

public String getSummary();
public void setSummary(String summary);

The message properties are defined as follows:

  • detail —Localized detail text for this FacesMessage (if any). This will generally be additional text that can help the user understand the context of the problem being reported by this FacesMessage, and offer suggestions for correcting it.

  • severity —A value defining how serious the problem being reported by this FacesMessage instance should be considered. Four standard severity values (SEVERITY_INFO, SEVERITY_WARN, SEVERITY_ERROR, and SEVERITY_FATAL) are defined as a typesafe enum in the FacesMessage class.

  • summary —Localized summary text for this FacesMessage. This is normally a relatively short message that concisely describes the nature of the problem being reported by this FacesMessage.

ResponseStream

ResponseStream is an abstract class representing a binary output stream for the current response. It has exactly the same method signatures as the java.io.OutputStream class.

ResponseWriter

ResponseWriter is an abstract class representing a character output stream for the current response. A ResponseWriter instance is obtained via a factory method on RenderKit. Please see RenderKit. It supports both low-level and high level APIs for writing character based information

public void close() throws IOException;
public void flush() throws IOException;
public void write(char c[]) throws IOException;
public void write(char c[], int off, int len) throws IOException;
public void write(int c) throws IOException;
public void write(String s) throws IOException;
public void write(String s, int off, int len) throws IOException;

The ResponseWriter class extends java.io.Writer, and therefore inherits these method signatures for low-level output. The close() method flushes the underlying output writer, and causes any further attempts to output characters to throw an IOException. The flush method flushes any buffered information to the underlying output writer, and commits the response. The write methods write raw characters directly to the output writer.

public abstract String getContentType();
public abstract String getCharacterEncoding();

Return the content type or character encoding used to create this ResponseWriter.

public void startCDATA();
public void endCDATA();

Start and end an XML CDATA Section..

public void startDocument() throws IOException;
public void endDocument() throws IOException;

Write appropriate characters at the beginning (startDocument) or end (endDocument) of the current response.

public void startElement(String name,
    UIComponent componentForElement) throws IOException;

Write the beginning of a markup element (the < character followed by the element name), which causes the ResponseWriter implementation to note internally that the element is open. This can be followed by zero or more calls to writeAttribute or writeURIAttribute to append an attribute name and value to the currently open element. The element will be closed (i.e. the trailing > added) on any subsequent call to startElement(), writeComment(), writeText(), endDocument(), close(), flush(), or write(). The componentForElement parameter tells the ResponseWriter which UIComponent this element corresponds to, if any. This parameter may be null to indicate that the element has no corresponding component. The presence of this parameter allows tools to provide their own implementation of ResponseWriter to allow the design time environment to know which component corresponds to which piece of markup.

public void endElement(String name) throws IOException;

Write a closing for the specified element, closing any currently opened element first if necessary.

public void writeComment(Object comment) throws IOException;

Write a comment string wrapped in appropriate comment delimiters, after converting the comment object to a String first. Any currently opened element is closed first.

public void writeAttribute(String name, Object value,
    String componentPropertyName) throws IOException;

public void writeURIAttribute(String name, Object value,
    String componentPropertyName) throws IOException;

These methods add an attribute name/value pair to an element that was opened with a previous call to startElement(), throwing an exception if there is no currently open element. The writeAttribute() method causes character encoding to be performed in the same manner as that performed by the writeText() methods. The writeURIAttribute() method assumes that the attribute value is a URI, and performs URI encoding (such as % encoding for HTML). The componentPropertyName, if present, denotes the property on the associated UIComponent for this element, to which this attribute corresponds. The componentPropertyName parameter may be null to indicate that this attribute has no corresponding property.

public void writeText(Object text, String property) throws IOException;
public void writeText(char text[], int off, int len) throws IOException;

Write text (converting from Object to String first, if necessary), performing appropriate character encoding and escaping. Any currently open element created by a call to startElement is closed first.

public abstract ResponseWriter cloneWithWriter(Writer writer);

Creates a new instance of this ResponseWriter, using a different Writer.

FacesContextFactory

A single instance of jakarta.faces.context.FacesContextFactory must be made available to each Jakarta Faces-based web application running in a servlet or portlet container. This class is primarily of use by Jakarta Faces implementors—applications will not generally call it directly. The factory instance can be acquired, by Jakarta Faces implementations or by application code, by executing:

FacesContextFactory factory = (FacesContextFactory)
    FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);

The FacesContextFactory implementation class provides the following method signature to create (or recycle from a pool) a FacesContext instance:

public FacesContext getFacesContext(Object context,
    Object request, Object response, Lifecycle lifecycle);

Create (if necessary) and return a FacesContext instance that has been configured based on the specified parameters. In a servlet environment, the first argument is a ServletContext, the second a ServletRequest and the third a ServletResponse.

ExceptionHandlerFactory

A single instance of jakarta.faces.context.ExceptionHandlerFactory must be made available to each Jakarta Faces-based web application running in a servlet or portlet container. The factory instance can be acquired, by Jakarta Faces implementations or by application code, by executing:

ExceptionHandlerFactory factory = (ExceptionHandlerFactory)
    FactoryFinder.getFactory(FactoryFinder.EXCEPTION_HANDLER_FACTORY);

The ExceptionHandlerFactory implementation class provides the following method signature to create an ExceptionHandler instance:

public ExceptionHandler getExceptionHandler(FacesContext currentContext);

Create and return a ExceptionHandler instance that has been configured based on the specified parameters.

ExternalContextFactory

A single instance of jakarta.faces.context.ExternalContextFactory must be made available to each Jakarta Faces-based web application running in a servlet or portlet container. This class is primarily of use by Jakarta Faces implementors—applications will not generally call it directly. The factory instance can be acquired, by Jakarta Faces implementations or by application code, by executing:

ExternalContextFactory factory = (ExternalContextFactory)
    FactoryFinder.getFactory(FactoryFinder.EXTERNAL_CONTEXT_FACTORY);

The ExternalContextFactory implementation class provides the following method signature to create (or recycle from a pool) a FacesContext instance:

public ExternalContext getExternalContext(
Object context, Object request, Object response);

Create (if necessary) and return an ExternalContext instance that has been configured based on the specified parameters. In a servlet environment, the first argument is a ServletContext, the second a ServletRequest and the third a ServletResponse.