When facing the problem of validating a property in a JSF2 application there are two main approaches.
Defining the validation on the ManagedBean using an Annotation
@ManagedBean
public class MyBean {
@Size(max=8)
private String s;
// Getters setters and other stuff.
}
or declaring it on the jsf page:
<h:inputText value="#{myBean.s}">
<f:validateLength maximum="8"/>
</h:inputText>
It happens that I can't decide for none of them. The first one is nice because it removes some code from the jsf pages (which is always good since those pages are not eye friendly by definition) but makes harder to see 'at a glance' what's going on with the page when checking the jsf file.
Which one do you think is clearer? Nicer? Better?
JSF provides inbuilt validators to validate its UI components. These tags can validate the length of the field, the type of input which can be a custom object. For these tags you need to use the following namespaces of URI in html node.
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.
The Bean Validation API is a Java specification which is used to apply constraints on object model via annotations. Here, we can validate a length, number, regular expression, etc. Apart from that, we can also provide custom validations. As Bean Validation API is just a specification, it requires an implementation.
Jakarta Bean Validation is a Java specification which. lets you express constraints on object models via annotations. lets you write custom constraints in an extensible way. provides the APIs to validate objects and object graphs. provides the APIs to validate parameters and return values of methods and constructors.
I would pump for validation on the ManagedBean, this removes logic from the JSF the VIEW in model view Controller. and should keep the JSF souly responsible for displaying the Model. Also having this on the managed bean ensures that where ever this is updated validation is applied. This is more DRY(Don't repeat yourself).
There is another advantage of the managedBean approach. If the information being displayed by the JSF is also available via a web service (WS) then the actual validation code can be factored out into a validation class and used for both the JSF and the WS ensuring that all information in the system is valid.
Richfaces allows you to use them together. See <rich:graphValidator>
(and beanValidator
as well).
These tags say: "apply JSF validation based on javax.validation
(or Hibernate validator) rules".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With