Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  JavaServer Faces Technology

5.  Introduction to Facelets

6.  Expression Language

7.  Using JavaServer Faces Technology in Web Pages

8.  Using Converters, Listeners, and Validators

9.  Developing with JavaServer Faces Technology

Managed Beans in JavaServer Faces Technology

Creating a Managed Bean

Using the EL to Reference Managed Beans

Writing Bean Properties

Writing Properties Bound to Component Values

UIInput and UIOutput Properties

UIData Properties

UISelectBoolean Properties

UISelectMany Properties

UISelectOne Properties

UISelectItem Properties

UISelectItems Properties

Writing Properties Bound to Component Instances

Writing Properties Bound to Converters, Listeners, or Validators

Writing Managed Bean Methods

Writing a Method to Handle Navigation

Writing a Method to Handle an Action Event

Writing a Method to Perform Validation

Writing a Method to Handle a Value-Change Event

10.  JavaServer Faces Technology: Advanced Concepts

11.  Using Ajax with JavaServer Faces Technology

12.  Composite Components: Advanced Topics and Example

13.  Creating Custom UI Components and Other Custom Objects

14.  Configuring JavaServer Faces Applications

15.  Java Servlet Technology

16.  Uploading Files with Java Servlet Technology

17.  Internationalizing and Localizing Web Applications

Part III Web Services

18.  Introduction to Web Services

19.  Building Web Services with JAX-WS

20.  Building RESTful Web Services with JAX-RS

21.  JAX-RS: Advanced Topics and Example

Part IV Enterprise Beans

22.  Enterprise Beans

23.  Getting Started with Enterprise Beans

24.  Running the Enterprise Bean Examples

25.  A Message-Driven Bean Example

26.  Using the Embedded Enterprise Bean Container

27.  Using Asynchronous Method Invocation in Session Beans

Part V Contexts and Dependency Injection for the Java EE Platform

28.  Introduction to Contexts and Dependency Injection for the Java EE Platform

29.  Running the Basic Contexts and Dependency Injection Examples

30.  Contexts and Dependency Injection for the Java EE Platform: Advanced Topics

31.  Running the Advanced Contexts and Dependency Injection Examples

Part VI Persistence

32.  Introduction to the Java Persistence API

33.  Running the Persistence Examples

34.  The Java Persistence Query Language

35.  Using the Criteria API to Create Queries

36.  Creating and Using String-Based Criteria Queries

37.  Controlling Concurrent Access to Entity Data with Locking

38.  Using a Second-Level Cache with Java Persistence API Applications

Part VII Security

39.  Introduction to Security in the Java EE Platform

40.  Getting Started Securing Web Applications

41.  Getting Started Securing Enterprise Applications

42.  Java EE Security: Advanced Topics

Part VIII Java EE Supporting Technologies

43.  Introduction to Java EE Supporting Technologies

44.  Transactions

45.  Resources and Resource Adapters

46.  The Resource Adapter Example

47.  Java Message Service Concepts

48.  Java Message Service Examples

49.  Bean Validation: Advanced Topics

50.  Using Java EE Interceptors

Part IX Case Studies

51.  Duke's Bookstore Case Study Example

52.  Duke's Tutoring Case Study Example

53.  Duke's Forest Case Study Example

Index

 

Using Bean Validation

Validating input received from the user to maintain data integrity is an important part of application logic. Validation of data can take place at different layers in even the simplest of applications, as shown in Developing a Simple Facelets Application. The guessnumber example application validates the user input (in the h:inputText tag) for numerical data at the presentation layer and for a valid range of numbers at the business layer.

JavaBeans Validation (Bean Validation) is a new validation model available as part of Java EE 6 platform. The Bean Validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component, such as a managed bean.

Constraints can be built in or user defined. User-defined constraints are called custom constraints. Several built-in constraints are available in the javax.validation.constraints package. Table 9-2 lists all the built-in constraints.

Table 9-2 Built-In Bean Validation Constraints

Constraint

Description

Example

@AssertFalse

The value of the field or property must be false.

@AssertFalse
boolean isUnsupported;

@AssertTrue

The value of the field or property must be true.

@AssertTrue
boolean isActive;

@DecimalMax

The value of the field or property must be a decimal value lower than or equal to the number in the value element.

@DecimalMax("30.00")
BigDecimal discount;

@DecimalMin

The value of the field or property must be a decimal value greater than or equal to the number in the value element.

@DecimalMin("5.00")
BigDecimal discount;

@Digits

The value of the field or property must be a number within a specified range. The integer element specifies the maximum integral digits for the number, and the fraction element specifies the maximum fractional digits for the number.

@Digits(integer=6, fraction=2)
BigDecimal price;

@Future

The value of the field or property must be a date in the future.

@Future
Date eventDate;

@Max

The value of the field or property must be an integer value lower than or equal to the number in the value element.

@Max(10)
int quantity;

@Min

The value of the field or property must be an integer value greater than or equal to the number in the value element.

@Min(5)
int quantity;

@NotNull

The value of the field or property must not be null.

@NotNull
String username;

@Null

The value of the field or property must be null.

@Null
String unusedString;

@Past

The value of the field or property must be a date in the past.

@Past
Date birthday;

@Pattern

The value of the field or property must match the regular expression defined in the regexp element.

@Pattern(regexp="\\(\\d{3}\\)\\d{3}-\\d{4}")
String phoneNumber;

@Size

The size of the field or property is evaluated and must match the specified boundaries. If the field or property is a String, the size of the string is evaluated. If the field or property is a Collection, the size of the Collection is evaluated. If the field or property is a Map, the size of the Map is evaluated. If the field or property is an array, the size of the array is evaluated. Use one of the optional max or min elements to specify the boundaries.

@Size(min=2, max=240)
String briefMessage;

In the following example, a constraint is placed on a field using the built-in @NotNull constraint:

public class Name {
    @NotNull 
    private String firstname;

    @NotNull 
    private String lastname;
}

You can also place more than one constraint on a single JavaBeans component object. For example, you can place an additional constraint for size of field on the firstname and the lastname fields:

public class Name {
    @NotNull
    @Size(min=1, max=16)
    private String firstname;

    @NotNull 
    @Size(min=1, max=16)
    private String lastname;
}

The following example shows a method with a user-defined constraint that checks for a predefined email address pattern such as a corporate email account:

@ValidEmail 
public String getEmailAddress() {
    return emailAddress;
}

For a built-in constraint, a default implementation is available. A user-defined or custom constraint needs a validation implementation. In the above example, the @ValidEmail custom constraint needs an implementation class.

Any validation failures are gracefully handled and can be displayed by the h:messages tag.

Any managed bean that contains Bean Validation annotations automatically gets validation constraints placed on the fields on a JavaServer Faces application’s web pages.

See Validating Persistent Fields and Properties for more information on using validation constraints.

Validating Null and Empty Strings

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all.

An empty string is represented as "". It is a character sequence of zero characters. A null string is represented by null. It can be described as the absence of a string instance.

Managed bean elements represented as a JavaServer Faces text component such as inputText are initialized with the value of the empty string by the JavaServer Faces implementation. Validating these strings can be an issue when user input for such fields is not required. Consider the following example, where the string testString is a bean variable that will be set using input typed by the user. In this case, the user input for the field is not required.

if (testString==null) {
    doSomething();
} else {
    doAnotherThing();
}

By default, the doAnotherThing method is called even when the user enters no data, because the testString element has been initialized with the value of an empty string.

In order for the Bean Validation model to work as intended, you must set the context parameter javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL to true in the web deployment descriptor file, web.xml:

<context-param>
    <param-name>
        javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL
    </param-name>
    <param-value>true</param-value>
</context-param>

This parameter enables the JavaServer Faces implementation to treat empty strings as null.

Suppose, on the other hand, that you have a @NotNull constraint on an element, meaning that input is required. In this case, an empty string will pass this validation constraint. However, if you set the context parameter javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL to true, the value of the managed bean attribute is passed to the Bean Validation runtime as a null value, causing the @NotNull constraint to fail.