Skip to main content

Trying out JBoss' Seam (Continued)

Posted by bleonard on May 30, 2006 at 12:55 PM PDT

In my previous blog entry I converted a standard JSF / EJB 3.0 application to one that uses JBoss' Seam framework. I covered Seam's primary feature, direct integration of JSF with EJB 3.0, eliminating the Managed Bean. In this entry, I'm going to show off Seam's validation support.

Getting Started
Adding Validation

In our simple registration application, we currently have 3 fields, 2 of which have a required length and a third which just can't be null. These constraints are currently managed in our view. For example, for username:



One obvious weakness to this approach is that any alternative views (MIDlet, Rich Client) would require implementation of the same constraints.

The Seam framework allows us to specify these constraints on the model directly. Seam incorporates the Hibernate Validator framework, which works regardless of your persistence provider. So for example, on the username property of our User entity, we can specify the following:



Try the following:

  1. Add the annotations above to the User.java entity class.
  2. Remove the constraints from the userName field in register.jsp.
  3. Open RegisterActionBean.java and add the @Valid annotation to the user field and the @IfInvalid annotation to the register method.







    The @Valid annotation forces validation on the User entity. The @IfInvalid annotation tells seem what to do in the case validation fails, which in this case is to redisplay the data entry page.


  4. Run the application. Enter a Real Name and Password but leave the Username field empty and try to Register.






  5. Complete the validation by adding a @Length annotation to the getPassword method and a @NotNull annotation to the getName() method. Don't forget to remove the validation code from the JSP.



    Here's the completed application. You'll have to resolve the same reference problems as you did in the previous blog entry.

Addendum

In order to display individual component messages, you just need to assign an HtmlMessage component to each of the input fields in your JSP. Note, for the association to work, you also have to add an id property to each of the input fields. Finally, notice the globalOnly property added to the HtmlMessages component. This prevents the individual component messages from being displayed twice.

componentmessages.png

I should also point out that since writing this blog I have learned that the @IfInvalid annotation has been deprecated. Support for the new s:validateAll and s:validate JSF tags will be in the next binary release of Seam, I assume 1.0.0CR4.

Related Topics >>