Web Development with Java and JSF: Bean Validation

Bean Validation

As stated before, Books is an application, maintained by just one author, who should know about the expected data. Thus, there is no user interface with immediate response after each input or lots of hints. Of course, those features are essential for an application for potentially “unknown” users. Later on, when developing Alumni, we will cover those features in detail. However, a validation is useful to prevent the user from entering data which might not fit the database.

Remember the JSF lifecycle: During phase 3, the input values will be converted and validated.Within the HTML page, every input is just treated as simple text. By the aid of the EL, these inputs are bound by value expressions to the data model. Usually this is done by the usage of properties of a Java bean. Within Java, all properties are strongly typed. Thus, conversations are needed, from text (String) to the target type and vice versa. This job is done by converters. JSF offers standard converters for a wide range of build in Java types. Later on, we will discuss custom converters. If a conversion fails, JSF throws an exception. According to this, converters perform a raw validation.

Beside this, JSF includes a couple of standard validators, which you may use to define a validation at a finer level, e.g. allow positive numbers only or force a string to a maximum length, and, and , and. We will cover this kind of validators later on.

A JSF validator will validate the input on server side just after the user entered it and before applying values the model. Sometimes only validating the input will not be enough. Data might be changed at the business layer. When persisting to a database the program might crash, because the data does not fit the database schema. It would be helpful to validate just before storing the data. Or at any other place within the application.

Luckily Java EE offers exactly this kind of validation, Bean Validation. And JSF takes advance of it and uses this validation too, if defined at the model the data is applied to.
In our application, we will edit and store information about books. We are going to add Bean Validation by simply applying special annotations to the book entity. Now, this validation will be used both by JSF and JPA. And if needed, you may call the validation programmatically.

Book entity

Every book is described by it’s title, subtitle, author and other information including a short description. This description might be presented to the user in different languages.
Thus, beside book, we need a second table containing the translations, like we did for the categories. For brevity, I’m going to present only essential parts of the entities. You may download the complete files. These are the two tables used for book and translation:

bookId        int
bookTitle   varchar(200)

[other columns omitted in this blog for brevity]

Next we define the book entity. Implement a property (field + getter and setter) for every column like we did before (see chapter JPA). The following excerpt shows just one property.

[...]
@Entity
@Table(name = "Book")
public class Book implements Serializable {
 [...]
 // <editor-fold defaultstate="collapsed" desc="Property Title">
 @Size(max = 200)
 @Column(name = "bookTitle")
 public String getTitle() {
 return _title;
 }
 public void setTitle(String title) {
 _title = title;
 }
 private String _title;
 // </editor-fold>
 [...]
}

The <editor fold> tags are specific to NetBeans and are used to collapse the code. They will be ignored by most other IDEs.

Let’s focus on the @Size(max = 200) annotation.

In my opinion this is a very self explaining annotation to check the size of the property which is limited to a maximum of 200 characters. This is exactly what we defined within the table. If the property title contains more characters, the validation will throw an exception. This validation takes place just before storing the data. This seems not to be much value, because whilst inserting / updating the database, we will get an exception, too.

But, as stated above, bean validation will be invoked by JSF also. And bean validation is not restricted to entities. You may annotate your DAO (data access object) class or any other kind of data model you’ve chosen. The annotation might be placed to a field or a property.

During the lifecycle phase 3, conversion and validation, JSF will invoke the JSF validators as well as Bean Validation. If a value expression, e.g. #{book.name} points to a property or field which is annotated for Bean Validation, then this check will be invoked.

There are a couple of annotations defined by Bean Validation. For example @Min and @Max to define integer limitations.
Or @Future and @Past to define date constraints. As you can see, these constraints seems to be very simple. Indeed, they are. Thus I renounce to explain it in detail.

One of the most sophisticated constrains is @Pattern, which compares the value of a property or field by pattern matching. For a list of possible constraints (as of Java EE 7), take a look into the [Java EE 7 tutorial]. An other useful source is [beanvalidation.org].

Bean Validation is included in a Java EE application server. It’s not part of a pure Servlet container or Java SE. Adding Bean Validation is just adding an appropriate library into your classpath. At beanvalidation.org you’ll find a list of certified implementations.

Book editor

If a validation failure occurs, this should be reported to the user. To do such, we need a placeholder for this message within our editor page. Let’s take a look onto this page.

<div class="inputGroup">
 <h:outputLabel styleClass="label" for="title" value="#{msg.lblTitle}"/>
 <h:inputText id="title" styleClass="inputFull"
 value="#{bookEditor.book.title}"/>
 <h:message id="msgTtitle" for="title" styleClass="warning"/>
 </div>

In this extract, we have a label, an input field and a message. This message will contain the validation message – if, and only if there is any. There is no need to place the message near by the input field. Both components are bound together by for=”title”.

The validation will be invoked in phase 3 of the JSF lifecycle. All possibly exceptions will be collected including the dedicated messages. If at least one exception occurs, the lifecycle will branch after phase 3 directly to phase 6, render response. The previous page will be re-rendered, including all messages.

Sometimes, the standard messages wont fit and you need to customize them. One approach is to add a ValidationMessages.properties file to the default package in the src\main\resources folder. Now, with the right properties within that file, you are able to customize the messages. The property names follow the structure `javax.validation.constraints.XXX.message`, where `XXX` represents the constraint name, e.g. `javax.validation.constraints.Size.message`. You’ll find a list for example at [grepcode]. If you need to translate the messages, simply add resource files with the proper locale code, like we did before.

Especial in case of the pattern matcher, a single message like `must match “{regexp}”` is not very useful to the user. Who outside the IT world would understand this? Depending on the pattern, we need different messages. Thus, we can’t use the properties file.
Bean Validation offers a simple solution: The message can be defined within the annotation.

`@Pattern(regexp = “.*@.*”, message = “Please enter a valid email address.”)`

(Ok, this is not a very sophisticated email checker. Just to show the principle.)

Although the message can be customized for every occurrence, there is a drawback.
This way, the message can’t be localized. Hopefully localization support will be added in the future.

 

This post I added to my tutorial is copied from the chapter Bean Validation of my book “Web Development with Java and JSF“. Books and Alumni are applications described in this book. References like “chapter JPA” refer to other chapters of this book.

Posted in NetBeans, Programming, Tutorial | Tagged , , | Leave a comment

Source code available

I finished the chapter “Internationalization and Localization” of my book “Web Development with Java and JSF” [1] . Now the book reached about 250 pages.

Source code for the applications as described so far is available from [2]. Developed with the current version of NetBeans and GlassFish.

 

[1] leanpub.com/jsf

[2] webdevelopment-java.info

 

Posted in NetBeans, Programming | Tagged , | Leave a comment

NetBeans 8.0.1 translated

Looking for a French, Spanish, German or other translation? Just a few days after its release, NetBeans 8.0.1 is available for a couple of different languages [1].

 

[1] http://bits.netbeans.org/netbeans/8.0.1/community/

Posted in NetBeans, Programming | Tagged , | Leave a comment

NetBeans 8.0.1 available

The latest version of NetBeans is available for download now [1]. For more information read the New and Noteworthy page [2].

 

[1] https://netbeans.org/downloads/

[2] http://wiki.netbeans.org/NewAndNoteworthyNB801

Posted in NetBeans | Leave a comment

Copy Static Resources on Save

Have you heard about the series “My top 5 NetBeans features”? NetBeans users report their favorite features. I just want to point out only one small (and almost hidden), but valuable feature, which is included in the upcoming version NetBeans 8.0.1.

Continue reading

Posted in NetBeans | Tagged , | Leave a comment