views.md 35.6 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
# 5. Rendering views

## 5.1. Introduction

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

## 5.2. 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:

<img src="images/flow-view-packaging.png" align="middle" />

Flow Packaging

## 5.3. Specifying view identifiers

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

### 5.3.1. 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">
			
```

### 5.3.2. 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">
			
```

### 5.3.3. 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.

## 5.4. 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.

### 5.4.1. 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" />
			
```

### 5.4.2. 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>
			
```

### 5.4.3. 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>
			
```

## 5.5. 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>
	    
```

## 5.6. 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.

## 5.7. Performing type conversion

When request parameters are used to populate the model (commonly referred to as data binding), type conversion is required to parse String-based request parameter values before setting target model properties.
Default type conversion is available for many common Java types such as numbers, primitives, enums, and Dates.
Users also have the ability to register their own type conversion logic for user-defined types, and to override the default Converters.

### 5.7.1. Type Conversion Options

Starting with version 2.1 Spring Web Flow uses the [type conversion](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/validation.html#core-convert) and [formatting](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/validation.html#format) system introduced in Spring 3 for nearly all type conversion needs.
Previously Web Flow applications used a type conversion mechanism that was different from the one in Spring MVC, which relied on the `java.beans.PropertyEditor` abstraction.
Spring 3 offers a modern type conversion alternative to PropertyEditors that was actually influenced by Web Flow's own type conversion system.
Hence Web Flow users should find it natural to work with the new Spring 3 type conversion.
Another obvious and very important benefit of this change is that a single type conversion mechanism can now be used across Spring MVC And Spring Web Flow.

### 5.7.2. Upgrading to Spring 3 Type Conversion And Formatting

What does this practically mean for existing applications?
Existing applications are likely registering their own converters of type `org.springframework.binding.convert.converters.Converter` through a sub-class of `DefaultConversionService` available in Spring Binding.
Those converters can continue to be registered as before.
They will be adapted as Spring 3 `GenericConverter` types and registered with a Spring 3 `org.springframework.core.convert.ConversionService` instance.
In other words existing converters will be invoked through Spring's type conversion service.

The only exception to this rule are named converters, which can be referenced from a `binding` element in a `view-state`:

```
public class ApplicationConversionService extends DefaultConversionService {
    public ApplicationConversionService() {
        addDefaultConverters();
        addDefaultAliases();
        addConverter("customConverter", new CustomConverter());
    }
}
				
```

```
<view-state id="enterBookingDetails" model="booking">
    <binder>
        <binding property="checkinDate" required="true" converter="customConverter" />
    </binder>
</view-state>
				
```

Named converters are not supported and cannot be used with the type conversion service available in Spring 3.
Therefore such converters will not be adapted and will continue to work as before, i.e. will not involve the Spring 3 type conversion.
However, this mechanism is deprecated and applications are encouraged to favor Spring 3 type conversion and formatting features.

Also note that the existing Spring Binding `DefaultConversionService` no longer registers any default converters.
Instead Web Flow now relies on the default type converters and formatters in Spring 3.

In summary the Spring 3 type conversion and formatting is now used almost exclusively in Web Flow.
Although existing applications will work without any changes, we encourage moving towards unifying the type conversion needs of Spring MVC and Spring Web Flow parts of applications.

### 5.7.3. Configuring Type Conversion and Formatting

In Spring MVC an instance of a `FormattingConversionService` is created automatically through the custom MVC namespace:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

	<mvc:annotation-driven/>

				
```

Internally that is done with the help of `FormattingConversionServiceFactoryBean`, which registers a default set of converters and formatters.
You can customize the conversion service instance used in Spring MVC through the `conversion-service` attribute:

```
<mvc:annotation-driven conversion-service="applicationConversionService" />
				
```

In Web Flow an instance of a Spring Binding `DefaultConversionService` is created automatically, which does not register any converters.
Instead it delegates to a `FormattingConversionService` instance for all type conversion needs.
By default this is not the same `FormattingConversionService` instance as the one used in Spring 3.
However that won't make a practical difference until you start registering your own formatters.

The `DefaultConversionService` used in Web Flow can be customized through the flow-builder-services element:

```
<webflow:flow-builder-services id="flowBuilderServices" conversion-service="defaultConversionService" />
				
```

Connecting the dots in order to register your own formatters for use in both Spring MVC and in Spring Web Flow you can do the following.
Create a class to register your custom formatters:

```
public class ApplicationConversionServiceFactoryBean extends FormattingConversionServiceFactoryBean {

    @Override
    protected void installFormatters(FormatterRegistry registry) {
        // ...
    }

}

				
```

Configure it for use in Spring MVC:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <mvc:annotation-driven conversion-service="applicationConversionService" />

    <!--
    	Alternatively if you prefer annotations for DI:
    	  1. Add @Component to the factory bean.
    	  2. Add a component-scan element (from the context custom namespace) here.
    	  3. Remove XML bean declaration below.
      -->

    <bean id="applicationConversionService" class="somepackage.ApplicationConversionServiceFactoryBean">

				
```

Connection the Web Flow `DefaultConversionService` to the same "applicationConversionService" bean used in Spring MVC:

```
    <webflow:flow-registry id="flowRegistry" flow-builder-services="flowBuilderServices" ... />

    <webflow:flow-builder-services id="flowBuilderServices" conversion-service="defaultConversionService" ... />

    <bean id="defaultConversionService" class="org.springframework.binding.convert.service.DefaultConversionService">
    	<constructor-arg ref="applicationConversionSevice"/>
    </bean>
				
```

Of course it is also possible to mix and match.
Register new Spring 3 `Formatter` types through the "applicationConversionService".
Register existing Spring Binding `Converter` types through the "defaultConversionService".

### 5.7.4. Working With Spring 3 Type Conversion And Formatting

An important concept to understand is the difference between type converters and formatters.

Type converters in Spring 3, provided in `org.springframework.core`, are for general-purpose type conversion between any two object types.
In addition to the most simple `Converter` type, two other interfaces are `ConverterFactory` and `GenericConverter`.

Formatters in Spring 3, provided in `org.springframework.context`, have the more specialized purpose of representing Objects as Strings.
The `Formatter` interface extends the `Printer` and `Parser` interfaces for converting an Object to a String and turning a String into an Object.

Web developers will find the `Formatter` interface most relevant because it fits the needs of web applications for type conversion.

|                                                                                                                                       ![[Note]](images/note.png)                                                                                                                                        |Note|
|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:---|
|An important point to be made is that Object-to-Object conversion is a generalization of the more specific Object-to-String conversion.<br/>In fact in the end `Formatters` are reigstered as `GenericConverter` types with Spring's `GenericConversionService` making them equal to any other converter.|    |

### 5.7.5. Formatting Annotations

One of the best features of the new type conversion is the ability to use annotations for a better control over formatting in a concise manner.
Annotations can be placed on model attributes and on arguments of @Controller methods that are mapped to requests.
Out of the box Spring provides two annotations `NumberFormat` and `DateTimeFormat` but you can create your own and have them registered along with the associated formatting logic.
You can see examples of the `DateTimeFormat` annotation in the [Spring Travel](https://src.springframework.org/svn/spring-samples/travel) and in the [Petcare](https://src.springframework.org/svn/spring-samples/petcare) along with other samples in the [Spring Samples](https://src.springframework.org/svn/spring-samples) repository.

### 5.7.6. Working With Dates

The `DateTimeFormat` annotation implies use of [Joda Time](http://joda-time.sourceforge.net/).
If that is present on the classpath the use of this annotation is enabled automatically.
By default neither Spring MVC nor Web Flow register any other date formatters or converters.
Therefore it is important for applications to register a custom formatter to specify the default way for printing and parsing dates.
The `DateTimeFormat` annotation on the other hand provides more fine-grained control where it is necessary to deviate from the default.

For more information on working with Spring 3 type conversion and formatting please refer to the relevant sections of the [Spring documentation](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/index.html).

## 5.8. 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>
		
```

## 5.9. Specifying bindings explicitly

Use the `binder` element to configure the exact set of model properties to
apply data binding to. This is useful to restrict the set of "allowed fields" per view.
Not using this could lead to a security issue, depending on the application domain and actual users,
since by default if the binder element is not specified all public properties of the model are
eligible for data binding by the view. By contrast when the `binder` element is specified,
only the explicitly configured bindings are allowed. Below is an example:

```
<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>

		
```

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.

## 5.10. Validating a model

Model validation is driven by constraints specified against a model object.
Web Flow supports enforcing such constraints programatically as well as
declaratively with JSR-303 Bean Validation annotations.

### 5.10.1. JSR-303 Bean Validation

Web Flow provides built-in support for the JSR-303 Bean Validation API
building on equivalent support available in Spring MVC.
To enable JSR-303 validation configure the flow-builder-services with
Spring MVC's `LocalValidatorFactoryBean`:

```
<webflow:flow-registry flow-builder-services="flowBuilderServices" />

<webflow:flow-builder-services id="flowBuilderServices" validator="validator" />

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
			
```

With the above in place, the configured validator will be applied to
all model attributes after data binding.

Note that JSR-303 bean validation and validation by convention
(explained in the next section) are not mutually exclusive.
In other words Web Flow will apply all available validation
mechanisms.

#### Partial Validation

JSR-303 Bean Validation supports partial validation through validation groups. For example:

```
@NotNull
@Size(min = 2, max = 30, groups = State1.class)
private String name;

```

In a flow definition you can specify validation hints on a view state
or on a transition and those will be resolved to validation groups.
For example:

```
<view-state id="state1" model="myModel" validation-hints="'group1,group2'">

```

The *validation-hints* attribute is an expression
that in the above example resolves to a comma-delimited String consisting
of the hints "group1" and "group2". A `ValidationHintResolver`is used to resolve these hints. The `BeanValidationHintResolver`used by default tries to resolve these strings to Class-based bean validation
groups. To do that it looks for matching inner types in the model or its parent.

For example given `org.example.MyModel` with inner types`Group1` and `Group2` it is
sufficient to supply the simple type names, i.e. "group1" and "group2".
You can also provide fully qualified type names.

A hint with the value "default" has a special meaning and is translated
to the default validation group in Bean Validation`javax.validation.groups.Default`.

A custom `ValidationHintResolver`can be configured if necessary through the validationHintResolver property
of the flow-builder-services element:

```
<webflow:flow-registry flow-builder-services="flowBuilderServices" />

<webflow:flow-builder-services id="flowBuilderServices" validator=".." validation-hint-resolver=".." />

```

### 5.10.2. 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.

#### Default validate method

A *Validator* class can also define a method called `validate` not associated (by convention) with any specific view-state.

```
@Component
public class BookingValidator {
    public void validate(Booking booking, ValidationContext context) {
        //...
    }
}
				
```

In the above code sample the method `validate` will be called every time a Model of type `Booking` is validated (unless validation has been suppressed for that transition).
If needed the default method can also be called in addition to an existing state-specific method. Consider the following example:

```
@Component
public class BookingValidator {
    public void validate(Booking booking, ValidationContext context) {
        //...
    }
    public void validateEnterBookingDetails(Booking booking, ValidationContext context) {
        //...
    }
}
				
```

In above code sample the method `validateEnterBookingDetails` will be called first.
The default `validate` method will be called next.

### 5.10.3. 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.

## 5.11. 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.

## 5.12. 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.

### 5.12.1. 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 a boolean
whose value, true or false, indicates whether the transition should take place or be prevented
from executing. A method may also return a String where the literal values "success", "yes", or
"true" indicate the transition should occur, and any other value means the opposite.
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.

### 5.12.2. 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>
			
```

### 5.12.3. 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.

### 5.12.4. 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.

## 5.13. 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.

### 5.13.1. 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());
			
```

### 5.13.2. 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());
			
```

### 5.13.3. 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}" />
			
```

### 5.13.4. 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.
			
```

## 5.14. 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.

## 5.15. 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.

### 5.15.1. Discarding history

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

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

### 5.15.2. 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">
			
```