开发者

Bean validation VS JSF validation

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' wh开发者_Python百科at's going on with the page when checking the jsf file.

Which one do you think is clearer? Nicer? Better?


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".


@user1730904, you can define messages in a resource bundle file as explained in Bean Validation specification document. The required steps are simple:

  1. Create a file named ValidationMessages_xx_XX.properties in some classpath folder (e.g. src/main/resources/). Where xx_XX is es_ES, en_US, etc. Where the content could be: field.message=The number of digits must be less or equal than {max}.
  2. Then use the value within the bean attribute annotation: @Size(max = 20, message="{field.message}")


I might prefer JSF validation because, I am unable to provide resource bundle error messages as part of bean validations. For example you can not do this

@NotNull(message = ResourceBundleHelper.getString("error_message"))

Because "Compile constants can only be primitives and Strings". There are work around to define the constant messages but that will look ugly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜