<?xml version="1.0" encoding="UTF-8"?>
<chapter id="spring-faces">
	<title>Spring Faces</title>
	<sect1 id="spring-faces-intro">
		<title>Introduction</title>
		<para>
			Spring Faces is the home of the new Spring Web Flow + JSF 1.2 integration layer, as well as a number of additional value adds specific
			to a JSF environment.  These value adds include:
		</para>
		<para>
			Unified EL Integration - A separate implementation of the <classname>ExpressionParser</classname> from Spring Binding that uses
			the new Unified EL from JSF 1.2 and JSP 2.1.  This allows for JSF users to use the same expression language in their flow definitions 
			as in their JSF views.
		</para>
		<para>
			Client Side Validator Components - A small set of JSF components that work as "advisors" on regular JSF inputText components.  These
			components make use of the rich validation capabilities of the Dojo javascript framework by default, with an alternate set of tags
			based on Ext also available.
		</para>
	</sect1>
	<sect1 id="jsf-webflow">
		<title>Web Flow Java Server Faces (JSF) integration</title>
		<para>
			The Spring Faces module provides strong integration between Spring Web Flow and Java Server Faces (JSF).  When used with JSF, 
			Spring Web Flow takes responsibility for view navigation handling and managing model state, adding power and 
			simplicity beyond JSF's default navigation system and object scopes.  Plain JSF views and components continue to work just as before,
			and are able to participate in flows with full access to flow state.  In addition, other view technologies
			such as Facelets continue to plug-in normally.
		</para>
		<para>
			The JSF integration relies on custom implementations of core JSF artifacts to drive the execution of flows.  In addition, 
			it relies on custom ELResolvers to access flow execution attributes from JSF components.
		</para>
    	<sect2 id="executor-jsf-simple">
    		<title>Adding Spring Web Flow extensions to a JSF application.</title>
			<para>
				Using Spring Web Flow in a JSF environment does not require any additions to the application's faces-config.xml.  The Spring Faces 
				jar just needs to be on the classpath and all of the custom JSF artifacts provided by spring-faces will be picked 
				up by JSF automatically.  Ideally, when building new applications from the start with Spring Faces, a faces-config.xml should
				not be needed at all in preference for having all beans managed by Spring.
			</para>
		</sect2>
    	<sect2 id="executor-jsf-simple-webflow-setup">
			<title>Configuring the Web Flow system</title>
			<para>
				The artifacts configured by Spring Faces use Spring to access the Web Flow system configuration.
				This requires the Spring Web Servlet to be configured in the web.xml deployment descriptor:
			</para>
			<programlisting>
&lt;!-- The front controller of the Spring Web application, responsible for handling all application requests --&gt;
&lt;servlet&gt;
	&lt;servlet-name&gt;Spring Web Servlet&lt;/servlet-name&gt;
	&lt;servlet-class&gt;org.springframework.webflow.servlet.SpringWebServlet&lt;/servlet-class&gt;
	&lt;init-param&gt;
		&lt;param-name&gt;configLocations&lt;/param-name&gt;
		&lt;param-value&gt;/WEB-INF/config/web-application-config.xml&lt;/param-value&gt;
	&lt;/init-param&gt;
	&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
		
&lt;!-- Map all /spring/* requests to the Spring Web Servlet for handling --&gt;
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;Spring Web Servlet&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/spring/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;				
			</programlisting>
			<para>
				The application context bootstrapped by the Spring Web Servlet should contain the Web Flow system configuration.
				The example <literal>webflow-config.xml</literal> below shows a typical Web Flow configuration for a JSF environment:
			</para>
	    	<programlisting>
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:web="http://www.springframework.org/schema/webflow-config"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/webflow-config
           http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd"&gt;

	&lt;!-- Imports the "application-layer" definining business logic and data access services --&gt;
	&lt;import resource="application-layer-config.xml"/&gt;
	
	&lt;web:flow-executor id="flowExecutor" flow-registry="flowRegistry"&gt;
		&lt;web:flow-execution-listeners&gt;
			&lt;web:listener ref="jpaFlowExecutionListener" criteria="*"/&gt;
		&lt;/web:flow-execution-listeners&gt;
	&lt;/web:flow-executor&gt;
	
	&lt;web:flow-registry id="flowRegistry" flow-builder-services="flowBuilderServices"&gt;
		&lt;web:flow-location path="flow/main/main.xml" /&gt;
		&lt;web:flow-location path="flow/booking/booking.xml" /&gt;
		&lt;web:flow-builder class="org.springframework.faces.ui.resource.ResourcesFlowBuilder" /&gt;
	&lt;/web:flow-registry&gt;

	&lt;bean id="flowBuilderServices" class="org.springframework.webflow.engine.builder.support.FlowBuilderServices"&gt;
		&lt;property name="expressionParser"&gt;
			&lt;bean class="org.springframework.webflow.core.expression.el.WebFlowELExpressionParser"&gt;
				&lt;constructor-arg &gt;
					&lt;bean class="org.jboss.el.ExpressionFactoryImpl"/&gt;
				&lt;/constructor-arg&gt;
			&lt;/bean&gt;
		&lt;/property&gt;
		&lt;property name="viewFactoryCreator"&gt;
			&lt;bean class="org.springframework.faces.webflow.JsfViewFactoryCreator"/&gt;
		&lt;/property&gt;
	&lt;/bean&gt;
		
&lt;/beans&gt;
	        </programlisting>
			<para>
				A bean named <literal>flowExecutor</literal> must be configured and linked with a flow definition registry
				that contains the flows eligible for execution.   Note the <literal>flowExecutor</literal> bean name is significant,
				as that is bean name the Web Flow JSF extensions will expect.
			</para>
			<para>		
				Any flow executor property such as the flow execution repository type is configurable here, consistent
				with the other environments Spring Web Flow supports.
			</para>
			<para>
				The <literal>flowRegistry</literal> bean definition shows the registration of two XML based flow definitions, as well
				as a special java-based FlowBuilder that installs a special flow for serving the javascript and CSS resources needed
				by the Spring Faces custom JSF components.
			</para>
			<para>
				The <literal>flowBuilderServices</literal> provides a number of JSF-specific services to the <literal>flowRegistry</literal>, including the
				<literal>WebFlowELExpressionParser</literal> that allows Web Flow to use the Unified EL for parsing expressions in flow definitions.  
			</para>
		</sect2>
		<sect2>
			<title>Configuring the FacesServlet</title>
			<para>
				Even in an ideal scenario where the <literal>SpringWebServlet</literal> is handling all incoming requests, the <literal>FacesServlet</literal>
				must still be configured in web.xml in order for JSF to bootstrap properly:
			</para>
			<programlisting>
&lt;!-- Here so the JSF implementation can initialize, not used at runtime --&gt;
&lt;servlet&gt;
	&lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
	&lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt;
	&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
	
&lt;!-- Mapping for faces initialization --&gt;
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
	&lt;url-pattern&gt;*.faces&lt;/url-pattern&gt;
&lt;/servlet-mapping>
			</programlisting>
			<para>
				This configuration also allows for the mixing of legacy pure JSF request handling with the request handling of Spring Web Flow for easier 
				page-by-page migration.
			</para>
		</sect2>
		<sect2 id="executor-jsf-launch-normal-anchor">
    		<title>Launching a flow execution - normal HTML anchor</title>
			<para>
				The preferred way of launching a flow from an external system, such as a normal JSF view is by accessing flow definition 
				URLs directly using a bookmark or normal HTML link:
			</para>
	    	<programlisting>
&lt;a href="/spring/main"&gt;Go&lt;/a&gt;
	    	</programlisting>
			<para>
				This link would launch the "main" flow, assuming /spring/* has been mapped to the <literal>SpringWebServlet</literal> defined within web.xml.
			</para>
    	</sect2>
    	<sect2 id="executor-jsf-launch-commandlink">
    		<title>Launching a flow execution - JSF command link component</title>
			<para>
				Before going this route, it should be considered whether the same effect can be achieved with a normal REST-ful URL link in combination perhaps
				in combination with a custom Web Flow <literal>action</literal> in order to execute specialized logic. If it is an absolute requirement to use
				a JSF UICommand component, then the recommended approach is to programmatically have JSF forward the request to the flow execution URL from within
				a JSF ActionListener.
			</para>
	    	<programlisting>
public void myActionListener(ActionEvent event) {
	// Execute any required processing and then forward to the flow execution
	
	facesContext.getCurrentInstance().getExternalContext().dispatch("/spring/main/");
	facesContext.getCurrentInstance().responseComplete();
}
	    	</programlisting>
    	</sect2>
    	<sect2 id="executor-jsf-sampleflow">
    		<title>Flow definitions in a JSF environment</title>
			<para>
				Flow definitions in a JSF environment are just plain Spring Web Flow definitions:
			</para>
			<programlisting>
&lt;?xml version="1.0" encoding="UTF-8"?>
&lt;flow xmlns="http://www.springframework.org/schema/webflow"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/webflow
                        http://www.springframework.org/schema/webflow/spring-webflow-1.0.xsd">

    &lt;var name="myBean" class="example.ManagedBeanImpl" scope="conversation" /&gt;
	
    &lt;start-state idref="displayView" /&gt;

    &lt;view-state id="displayView" view="myview.jsp"&gt;
        &lt;transition on="submit" to="prepareNextView"/&gt;
    &lt;/view-state>
    
    &lt;action-state id="prepareNextView" &gt;
    	&lt;bean-action bean="myService" method="loadMyModel"&gt;
    		&lt;method-arguments&gt;
    			&lt;argument expression="#{myBean.foo}"/&gt;
    		&lt;/method-arguments&gt;
    	&lt;/bean-action&gt;
    	&lt;transition on="success" to="displayNextView"/&gt;
    &lt;/action-state&gt;

    &lt;view-state id="displayNextView" view="mynextview.jsp" /&gt;

&lt;/flow&gt;				
			</programlisting> 
			<para>
  				A primary benefit of using JSF is it is a rich UI component framework, and UI components have both data and behavior.
				As JSF components typically handle data binding and field-level validation behaviors, the actual flow
				definition logic is often simpler and more focused as a result.
			</para>
			<para>
				An important difference to note in the above example is the difference in using EL expressions versus Web Flow's traditional
				OGNL expressions.  When using the ELExpressionParser, the chain of configured resolvers will automatically resolve an expression
				against the correct scope, so the "conversationScope" identifier is optional in the expression when referencing "myBean".
			</para>
			<para>
  				Views selected by view states are specified using paths relative to the current flow definition.  In the above example, it is
  				expected that myview.jsp and mynextview.jsp are both located in the same directory as the flow definition.
			</para>
		</sect2>
    	<sect2 id="executor-jsf-resume-form">
    		<title>Resuming a flow execution - form bound to flow execution variables</title>
			<para>
				Views participating in flows are just plain JSF views.  They may also incorporate other
				JSF view technologies such as Facelets and Ajax4JSF.
			</para>
	    	<programlisting>
&lt;f:view&gt;		
    &lt;h:form id="form"&gt;
        ...
        &lt;h:inputText id="propertyName" value="#{someBean.someProperty}"/&gt;
        ...
        &lt;h:commandButton type="submit" value="Next" action="submit"/&gt;
    &lt;/h:form&gt;
&lt;/f:view&gt;		
	    	</programlisting>
			<para>
				As shown above, there is nothing Spring Web Flow specific here.  The flow execution
				key is automatically tracked by a special UI component in the view root, so there is no need to 
				track it manually.  Action outcomes are automatically mapped to Spring Web Flow event identifiers
				signaled against the current state.
			</para>
    	</sect2>
    	<sect2 id="spring-faces-components">
    		<title>Spring Faces JSF Components</title>
    	    <para>
    	    	Spring Faces provides some lightweight JSF components that act in an "advisor" role to provide rich client-side validation
    	    	capabilities to standard inputText components.  These can be used in place of server-side JSF validators to provide immediate
    	    	validation feedback to the end user without the overhead of another fine-grained call to the server.  The default implementation 
    	    	of these components use the Dojo javascript library to provide this validation behavior.  Dojo was chosen due to their increased
    	    	attention to accessibility concerns compared to other javascript frameworks.  An alternate implementation based on the Ext library
    	    	is also provided.  Though Ext does not address accessibility issues, it can still be attractive for use in internal corporate 
    	    	intranet style applications.  
    	    </para>
    	    <sect3>
    	    	<title>Spring Faces Component Configuration</title>
    	    	<para>
    	    		The Spring Faces components are currently provided as Facelets tags.  In order to utilize them, the 
    	    		following namespace declaration must be added to the header of a Facelets view template:      
    	    	</para>
    	    	<programlisting>
xmlns:sf="http://www.springframework.org/tags/faces"
    	    	</programlisting>
    	    </sect3>
    	    <sect3>
    	    	<title>Spring Faces Resource Loading</title>
    	    	<para>
    	    		Spring Faces requires the installation of a special flow for loading javascript and CSS resources, as shown in the configuration
    	    		example.  This special stateless flow serves up resources corresponding to URLs such as "/spring/resources/dojo/dojo.js".  This flow
    	    		searches for the corresponding resource as follows:
    	    		<orderedlist>
    	    			<listitem>
    	    				1) Look for the resource in the web app root using the context-relative path "/dojo/dojo.js", and serve the resource if found.
    	    			</listitem>
    	    			<listitem>
    	    				2) If not found in the web app root, try and load the resource from the classpath using the path "/META-INF/dojo/dojo.js" and
    	    				serve the resource if found.
    	    			</listitem>
    	    		</orderedlist>
    	    	</para>
    	    	<para>
    	    		For convenience, the external javascript libraries that the Spring Faces components depend on are made available in seperate
    	    		jar files, and will be automatically loaded by the components when needed using the proper resource URLs.  Since the resource loading 
    	    		mechanism checks in the web app classpath first it is possible to, for example, override the provided resources with a custom build of the 
    	    		Dojo or Ext library that is optimized for the particular application.
    	    	</para>
    	    </sect3>
    	    <sect3>
    	    	<title>Using The Spring Faces Client Side Validation Components</title>
    	    	<para>
    	    		Spring Faces provides three different client-side validator components:
    	    	</para>
    	    	<para>
    				<orderedlist>
    					<listitem>
    						<para>
    							&lt;sf:clientTextValidator&gt; - Provides validation with customizable error messages for text fields. 
    						</para>
    					</listitem>
    					<listitem>
    						<para>
    							&lt;sf:clientNumberValidator&gt; - Provides validation and input filtering with customizable error messages for numeric 
    							fields. 
    						</para>
    					</listitem>
    					<listitem>
    						<para>
    							&lt;sf:clientDateValidator&gt; - Provides validation and a rich popup date picker control with customizable error 
    							messages for date fields. 
    						</para>
    					</listitem>
    					<listitem>
    						<para>
    							&lt;sf:validateAllOnClick&gt; - When wrapped around a UICommand component such as &lt;h:commandButton&gt; or &lt;h:commandLink&gt;
    							fires all client-side validators when the UICommand component is clicked and prevents the form from being submitted if 
    							any of the validations fail.
    						</para>
    					</listitem>
    				</orderedlist>
    			</para>
    			<para>
    				The validator components must be wrapped around an &lt;h:inputText&gt; component (or any other component that renders an HTML text input).
    				For example, see the following snippet from the Booking sample application:
    			</para>  
    			<para>
    				<programlisting>
&lt;sf:clientDateValidator required="true"&gt;
	&lt;h:inputText id="checkinDate" value="#{booking.checkinDate}" required="true"&gt;
		&lt;f:convertDateTime pattern="yyyy-MM-dd" timeZone="EST"/&gt;
	&lt;/h:inputText&gt;
&lt;/sf:clientDateValidator&gt;
    				</programlisting>
    			</para>
    			<para>
    				In general, each of the available validations has a corresponding sensible default error message.  The error messages
    				can be overridden via the component's "invalidMessage" attribute.  All of the customizable message attributes are
    				value-binding aware so that expressions may be used to bind to keys in the application message bundle if so desired.   
    			</para>
    			<para>
    				Please refer to the javadocs of the component classes to see all of the attributes for the components.  More 
					extensive taglib docs will be available with the final release of Spring Web Flow 2.0.
    			</para>
    	    </sect3>
    	    <sect3>
    	    	<title>Using Ext Version of The Spring Faces Client Side Validation Components</title>
    	    	<para>
    	    		An alternate version of the components based on the Ext library is provided under a separate tag namespace. 
    	    		In order to utilize them, the following namespace declaration must be added to the header of a Facelets view template:      
    	    	</para>
    	    	<programlisting>
xmlns:sfe="http://www.springframework.org/tags/faces-ext"
    	    	</programlisting>
				<para>
					The basic behavior of the Ext versions of the components is the same, but the tags have different attributes that correspond with the attributes
					of the underlying Ext widgets.  Please refer to the javadocs of the component classes to see all of the attributes for the components.  More 
					extensive taglib docs will be available with the final release of Spring Web Flow 2.0.
				</para>
    	    </sect3>
    	</sect2>
		<sect2 id="executor-jsf-sample">
			<title>Spring Web Flow JSF Integration Samples</title>
			<para>
				See the booking-jsf sample that provides a complete example of Spring Web Flow 
				operating in a JSF environment, including use of flow-managed persistence, EL integration, and the
				client-side JSF validator components of Spring Faces.
			</para>
		</sect2>
    </sect1>	   
</chapter>