# Rendering views

## Introduction

This chapter shows you how to use the `view-state` element to render views within a flow.

## Defining view states

Use the `view-state` element to define a step of the flow that renders a view and waits for a user event to resume:

    <view-state id="enterBookingDetails">
        <transition on="submit" to="reviewBooking" />
    </view-state>

By convention, a view-state maps its id to a view template in the directory where the flow is located. For example, the state above might render `/WEB-INF/hotels/booking/enterBookingDetails.xhtml` if the flow itself was located in the `/WEB-INF/hotels/booking` directory.

Below is a sample directory structure showing views and other resources like message bundles co-located with their flow definition:

Flow Packaging

## Specifying view identifiers

Use the `view` attribute to specify the id of the view to render explicitly.

### Flow relative view ids

The view id may be a relative path to view resource in the flow's working directory:

    <view-state id="enterBookingDetails" view="bookingDetails.xhtml">

### Absolute view ids

The view id may be a absolute path to a view resource in the webapp root directory:

    <view-state id="enterBookingDetails" view="/WEB-INF/hotels/booking/bookingDetails.xhtml">

### Logical view ids

With some view frameworks, such as Spring MVC's view framework, the view id may also be a logical identifier resolved by the framework:

    <view-state id="enterBookingDetails" view="bookingDetails">

See the Spring MVC integration section for more information on how to integrate with the MVC `ViewResolver` infrastructure.

## View scope

A view-state allocates a new `viewScope` when it enters. This scope may be referenced within the view-state to assign variables that should live for the duration of the state. This scope is useful for manipulating objects over a series of requests from the same view, often Ajax requests. A view-state destroys its viewScope when it exits.

### Allocating view variables

Use the `var` tag to declare a view variable. Like a flow variable, any `@Autowired` references are automatically restored when the view state resumes.

    <var name="searchCriteria" class="com.mycompany.myapp.hotels.SearchCriteria" />

### Assigning a viewScope variable

Use the `on-render` tag to assign a variable from an action result before the view renders:

    <on-render>
        <evaluate expression="bookingService.findHotels(searchCriteria)" result="viewScope.hotels" />
    </on-render>

### Manipulating objects in view scope

Objects in view scope are often manipulated over a series of requests from the same view. The following example pages through a search results list. The list is updated in view scope before each render. Asynchronous event handlers modify the current data page, then request re-rendering of the search results fragment.

    <view-state id="searchResults">
        <on-render>
            <evaluate expression="bookingService.findHotels(searchCriteria)"
                      result="viewScope.hotels" />
        </on-render>
        <transition on="next">
            <evaluate expression="searchCriteria.nextPage()" />
            <render fragments="searchResultsFragment" />
        </transition>
        <transition on="previous">
            <evaluate expression="searchCriteria.previousPage()" />
            <render fragments="searchResultsFragment" />
        </transition>
    </view-state>

## Executing render actions

Use the `on-render` element to execute one or more actions before view rendering. Render actions are executed on the initial render as well as any subsequent refreshes, including any partial re-renderings of the view.

    <on-render>
        <evaluate expression="bookingService.findHotels(searchCriteria)" result="viewScope.hotels" />
    </on-render>

## Binding to a model

Use the `model` attribute to declare a model object the view binds to. This attribute is typically used in conjunction with views that render data controls, such as forms. It enables form data binding and validation behaviors to be driven from metadata on your model object.

The following example declares an `enterBookingDetails` state manipulates the `booking` model:

    <view-state id="enterBookingDetails" model="booking">

The model may be an object in any accessible scope, such as `flowScope` or `viewScope`. Specifying a `model` triggers the following behavior when a view event occurs:

1. View-to-model binding. On view postback, user input values are bound to model object properties for you.

2. Model validation. After binding, if the model object requires validation that validation logic will be invoked.

For a flow event to be generated that can drive a view state transition, model binding must complete successfully. If model binding fails, the view is re-rendered to allow the user to revise their edits.

## Performing type conversion

When a model binding occurs during view postback, the binding system will attempt to convert the input value to the type of the target model property if necessary. Default Converters are registered for common types such as Numbers, primitives, enums, and Dates and are applied automatically. Users also have the ability to register their own converters for user-defined types, and to override the default Converters.

### Implementing a Converter

To implement your own Converter, implement the `org.springframework.binding.convert.converters.TwoWayConverter` interface. A convenient `StringToObject` base class has been provided to simplify the implementation of this interface for converters that convert from a user input String to a user-defined Object and back. Simply extend from this class and override these two methods:

    protected abstract Object toObject(String string, Class targetClass) throws Exception;

    protected abstract String toString(Object object) throws Exception;

`toObject(String, Class)` should convert from the input string to your object's type, and `toString(Object)` should do the reverse.

The following example shows a Converter that converts from String to a MonetaryAmount for working with currency values:

    public class StringToMonetaryAmount extends StringToObject {

       public StringToMonetaryAmount() {
           super(MonetaryAmount.class);
       }

       @Override
       protected Object toObject(String string, Class targetClass) {
           return MonetaryAmount.valueOf(string);
       }

       @Override
       protected String toString(Object object) {
           MonetaryAmount amount = (MonetaryAmount) object;
           return amount.toString();
       }
    }

Review the pre-built converters in the `org.springframework.binding.convert.converters` package to see more examples of Converter implementations.

### Registering a Converter

To install your own Converter or override any of the default Converters, extend from `org.springframework.binding.convert.service.DefaultConversionService` and override the `addDefaultConverters()` method. Use the `addConverter(Converter)` method to register the primary Converter to use to convert between two types, such as a `String` and a `MonetaryAmount`. Optionally use the `addConverter(String, Converter)` method to register alternate converters for the same type pair; for example, to support formatting a `java.util.Date` as a String in several different ways.

Each alternate Converter is indexed by a unique `converterId` that can be referenced when configuring a model binding. When no converter id is referenced explicitly by a binding, the primary Converter between the two types is always used.

The ConversionService is the object Web Flow consults at runtime to lookup conversion executors to convert from one type to another. There is generally one ConversionService per application. See the System Setup section for documentation on how to configure an extended ConversionService implementation that registers custom Converters to apply application-wide. Also consult the Convert API documentation for more information.

## Suppressing binding

Use the `bind` attribute to suppress model binding and validation for particular view events. The following example suppresses binding when the `cancel` event occurs:

    <view-state id="enterBookingDetails" model="booking">
        <transition on="proceed" to="reviewBooking">
        <transition on="cancel" to="bookingCancelled" bind="false" />
    </view-state>

## Specifying bindings explicitly

Use the `binder` element to configure the exact set of model bindings usable by the view. This is particularly useful in a Spring MVC environment for restricting the set of "allowed fields" per view.

    <view-state id="enterBookingDetails" model="booking">
        <binder>
            <binding property="creditCard" />
            <binding property="creditCardName" />
            <binding property="creditCardExpiryMonth" />
            <binding property="creditCardExpiryYear" />
        </binder>
        <transition on="proceed" to="reviewBooking" />
        <transition on="cancel" to="cancel" bind="false" />
    </view-state>

If the binder element is not specified, all public properties of the model are eligible for binding by the view. With the binder element specified, only the explicitly configured bindings are allowed.

Each binding may also apply a converter to format the model property value for display in a custom manner. If no converter is specified, the default converter for the model property's type will be used.

    <view-state id="enterBookingDetails" model="booking">
        <binder>
            <binding property="checkinDate" converter="shortDate" />
            <binding property="checkoutDate" converter="shortDate" />
            <binding property="creditCard" />
            <binding property="creditCardName" />
            <binding property="creditCardExpiryMonth" />
            <binding property="creditCardExpiryYear" />
        </binder>
        <transition on="proceed" to="reviewBooking" />
        <transition on="cancel" to="cancel" bind="false" />
    </view-state>

In the example above, the `shortDate` converter is bound to the `checkinDate` and `checkoutDate` properties. Custom converters may be registered with the application's ConversionService.

Each binding may also apply a required check that will generate a validation error if the user provided value is null on form postback:

    <view-state id="enterBookingDetails" model="booking">
        <binder>
            <binding property="checkinDate" converter="shortDate" required="true" />
            <binding property="checkoutDate" converter="shortDate" required="true" />
            <binding property="creditCard" required="true" />
            <binding property="creditCardName" required="true" />
            <binding property="creditCardExpiryMonth" required="true" />
            <binding property="creditCardExpiryYear" required="true" />
        </binder>
        <transition on="proceed" to="reviewBooking">
        <transition on="cancel" to="bookingCancelled" bind="false" />
    </view-state>

In the example above, all of the bindings are required. If one or more blank input values are bound, validation errors will be generated and the view will re-render with those errors.

## Validating a model

Model validation is driven by constraints specified against a model object. Web Flow supports enforcing such constraints programatically.

### Programmatic validation

There are two ways to perform model validation programatically. The first is to implement validation logic in your model object. The second is to implement an external `Validator`. Both ways provide you with a `ValidationContext` to record error messages and access information about the current user.

#### Implementing a model validate method

Defining validation logic in your model object is the simplest way to validate its state. Once such logic is structured according to Web Flow conventions, Web Flow will automatically invoke that logic during the view-state postback lifecycle. Web Flow conventions have you structure model validation logic by view-state, allowing you to easily validate the subset of model properties that are editable on that view. To do this, simply create a public method with the name `validate${state}`, where `${state}` is the id of your view-state where you want validation to run. For example:

    public class Booking {
        private Date checkinDate;
        private Date checkoutDate;
        ...

        public void validateEnterBookingDetails(ValidationContext context) {
            MessageContext messages = context.getMessageContext();
            if (checkinDate.before(today())) {
                messages.addMessage(new MessageBuilder().error().source("checkinDate").
                    defaultText("Check in date must be a future date").build());
            } else if (!checkinDate.before(checkoutDate)) {
                messages.addMessage(new MessageBuilder().error().source("checkoutDate").
                    defaultText("Check out date must be later than check in date").build());
            }
        }
    }

In the example above, when a transition is triggered in a `enterBookingDetails` view-state that is editing a `Booking` model, Web Flow will invoke the `validateEnterBookingDetails(ValidationContext)` method automatically unless validation has been suppressed for that transition. An example of such a view-state is shown below:

    <view-state id="enterBookingDetails" model="booking">
        <transition on="proceed" to="reviewBooking">
    </view-state>

Any number of validation methods are defined. Generally, a flow edits a model over a series of views. In that case, a validate method would be defined for each view-state where validation needs to run.

#### Implementing a Validator

The second way is to define a separate object, called a Validator, which validates your model object. To do this, first create a class whose name has the pattern ${model}Validator, where `${model}` is the capitialized form of the model expression, such as `booking`. Then define a public method with the name `validate${state}`, where `${state}` is the id of your view-state, such as `enterBookingDetails`. The class should then be deployed as a Spring bean. Any number of validation methods can be defined. For example:

    @Component
    public class BookingValidator {
        public void validateEnterBookingDetails(Booking booking, ValidationContext context) {
            MessageContext messages = context.getMessageContext();
            if (booking.getCheckinDate().before(today())) {
                messages.addMessage(new MessageBuilder().error().source("checkinDate").
                    defaultText("Check in date must be a future date").build());
            } else if (!booking.getCheckinDate().before(booking.getCheckoutDate())) {
                messages.addMessage(new MessageBuilder().error().source("checkoutDate").
                    defaultText("Check out date must be later than check in date").build());
            }
        }
    }

In the example above, when a transition is triggered in a `enterBookingDetails` view-state that is editing a `Booking` model, Web Flow will invoke the `validateEnterBookingDetails(Booking, ValidationContext)` method automatically unless validation has been suppressed for that transition.

A Validator can also accept a Spring MVC `Errors` object, which is required for invoking existing Spring Validators.

Validators must be registered as Spring beans employing the naming convention `${model}Validator` to be detected and invoked automatically. In the example above, Spring 2.5 classpath-scanning would detect the `@Component` and automatically register it as a bean with the name `bookingValidator`. Then, anytime the `booking` model needs to be validated, this `bookingValidator` instance would be invoked for you.

### ValidationContext

A ValidationContext allows you to obtain a `MessageContext` to record messages during validation. It also exposes information about the current user, such as the signaled `userEvent` and the current user's `Principal` identity. This information can be used to customize validation logic based on what button or link was activated in the UI, or who is authenticated. See the API Javadocs for `ValidationContext` for more information.

## Suppressing validation

Use the `validate` attribute to suppress model validation for particular view events:

    <view-state id="chooseAmenities" model="booking">
        <transition on="proceed" to="reviewBooking">
        <transition on="back" to="enterBookingDetails" validate="false" />
    </view-state>

In this example, data binding will still occur on `back` but validation will be suppressed.

## Executing view transitions

Define one or more `transition` elements to handle user events that may occur on the view. A transition may take the user to another view, or it may simply execute an action and re-render the current view. A transition may also request the rendering of parts of a view called "fragments" when handling an Ajax event. Finally, "global" transitions that are shared across all views may also be defined.

Implementing view transitions is illustrated in the following sections.

### Transition actions

A view-state transition can execute one or more actions before executing. These actions may return an error result to prevent the transition from exiting the current view-state. If an error result occurs, the view will re-render and should display an appropriate message to the user.

If the transition action invokes a plain Java method, the invoked method may return false to prevent the transition from executing. This technique can be used to handle exceptions thrown by service-layer methods. The example below invokes an action that calls a service and handles an exceptional situation:

    <transition on="submit" to="bookingConfirmed">
        <evaluate expression="bookingAction.makeBooking(booking, messageContext)" />
    </transition>

    public class BookingAction {
       public boolean makeBooking(Booking booking, MessageContext context) {
           try {
               bookingService.make(booking);
               return true;
           } catch (RoomNotAvailableException e) {
               context.addMessage(new MessageBuilder().error().
                   .defaultText("No room is available at this hotel").build());
               return false;
           }
       }
    }

When there is more than one action defined on a transition, if one returns an error result the remaining actions in the set will not be executed. If you need to ensure one transition action's result cannot impact the execution of another, define a single transition action that invokes a method that encapsulates all the action logic.

### Global transitions

Use the flow's `global-transitions` element to create transitions that apply across all views. Global-transitions are often used to handle global menu links that are part of the layout.

    <global-transitions>
        <transition on="login" to="login" />
        <transition on="logout" to="logout" />
    </global-transitions>

### Event handlers

From a view-state, transitions without targets can also be defined. Such transitions are called "event handlers":

    <transition on="event">
        <!-- Handle event -->
    </transition>

These event handlers do not change the state of the flow. They simply execute their actions and re-render the current view or one or more fragments of the current view.

### Rendering fragments

Use the `render` element within a transition to request partial re-rendering of the current view after handling the event:

    <transition on="next">
        <evaluate expression="searchCriteria.nextPage()" />
        <render fragments="searchResultsFragment" />
    </transition>

The fragments attribute should reference the id(s) of the view element(s) you wish to re-render. Specify multiple elements to re-render by separating them with a comma delimiter.

Such partial rendering is often used with events signaled by Ajax to update a specific zone of the view.

## Working with messages

Spring Web Flow's `MessageContext` is an API for recording messages during the course of flow executions. Plain text messages can be added to the context, as well as internationalized messages resolved by a Spring `MessageSource`. Messages are renderable by views and automatically survive flow execution redirects. Three distinct message severities are provided: `info`, `warning`, and `error`. In addition, a convenient `MessageBuilder` exists for fluently constructing messages.

### Adding plain text messages

    MessageContext context = ...
    MessageBuilder builder = new MessageBuilder();
    context.addMessage(builder.error().source("checkinDate")
        .defaultText("Check in date must be a future date").build());
    context.addMessage(builder.warn().source("smoking")
        .defaultText("Smoking is bad for your health").build());
    context.addMessage(builder.info()
        .defaultText("We have processed your reservation - thank you and enjoy your stay").build());

### Adding internationalized messages

    MessageContext context = ...
    MessageBuilder builder = new MessageBuilder();
    context.addMessage(builder.error().source("checkinDate").code("checkinDate.notFuture").build());
    context.addMessage(builder.warn().source("smoking").code("notHealthy")
        .resolvableArg("smoking").build());
    context.addMessage(builder.info().code("reservationConfirmation").build());

### Using message bundles

Internationalized messages are defined in message bundles accessed by a Spring `MessageSource`. To create a flow-specific message bundle, simply define `messages.properties` file(s) in your flow's directory. Create a default `messages.properties` file and a .properties file for each additional `Locale` you need to support.

    #messages.properties
    checkinDate=Check in date must be a future date
    notHealthy={0} is bad for your health
    reservationConfirmation=We have processed your reservation - thank you and enjoy your stay

From within a view or a flow, you may also access message resources using the `resourceBundle` EL variable:

    <h:outputText value="#{resourceBundle.reservationConfirmation}" />

### Understanding system generated messages

There are several places where Web Flow itself will generate messages to display to the user. One important place this occurs is during view-to-model data binding. When a binding error occurs, such as a type conversion error, Web Flow will map that error to a message retrieved from your resource bundle automatically. To lookup the message to display, Web Flow tries resource keys that contain the binding error code and target property name.

As an example, consider a binding to a `checkinDate` property of a `Booking` object. Suppose the user typed in a alphabetic string. In this case, a type conversion error will be raised. Web Flow will map the 'typeMismatch' error code to a message by first querying your resource bundle for a message with the following key:

    booking.checkinDate.typeMismatch

The first part of the key is the model class's short name. The second part of the key is the property name. The third part is the error code. This allows for the lookup of a unique message to display to the user when a binding fails on a model property. Such a message might say:

    booking.checkinDate.typeMismatch=The check in date must be in the format yyyy-mm-dd.

If no such resource key can be found of that form, a more generic key will be tried. This key is simply the error code. The field name of the property is provided as a message argument.

    typeMismatch=The {0} field is of the wrong type.

## Displaying popups

Use the `popup` attribute to render a view in a modal popup dialog:

    <view-state id="changeSearchCriteria" view="enterSearchCriteria.xhtml" popup="true">

When using Web Flow with the Spring Javascript, no client side code is necessary for the popup to display. Web Flow will send a response to the client requesting a redirect to the view from a popup, and the client will honor the request.

## View backtracking

By default, when you exit a view state and transition to a new view state, you can go back to the previous state using the browser back button. These view state history policies are configurable on a per-transition basis by using the `history` attribute.

### Discarding history

Set the history attribute to `discard` to prevent backtracking to a view:

    <transition on="cancel" to="bookingCancelled" history="discard">

### Invalidating history

Set the history attribute to `invalidate` to prevent backtracking to a view as well all previously displayed views:

    <transition on="confirm" to="bookingConfirmed" history="invalidate">