JSF根据验证从bean更新值的正确方法 [英] JSF correct way to update a value from a bean depending on validation
问题描述
我有一个与页面关联的bucking bean,我想根据验证是否成功来更改其值.
I have a bucking bean associated to a page and I want to change its value depending on whether a validation failed or succeeded.
@ManagedBean(name = "testBean")
@ViewScoped()
public class TestBean implements Serializable {
String value="";
int number;
/*getters-setters*/
}
一个验证器,用于检查数字是否为正
a validator that checks if the number is positive
@FacesValidator("Validator")
public class NumValidator implements Validator{
@Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
int num=(Integer)value;
if(num<0){
FacesMessage msg =
new FacesMessage(The number is negative");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
}
和一个xhmtl页面:
and a xhmtl page:
<h:form>
<h:inputText id="number" value="#{testBean.number}" required="true"
requiredMessage="Is">
<f:validator validatorId="Validator" />
<f:ajax event="blur" render="msg" />
</h:inputText>
<h:message id="msg" for="number"/>
</h:form>
并且我希望Bean中的String不管值是value ="negative"或value ="positive".该怎么办?
And I want the String in the bean to be value="negative" or value="positive" whether the occastion. How can this be done?
推荐答案
您的具体功能要求可归结为:
Your concrete functional requirement appears to boil down to:
当发生验证错误时,如何更改
< h:inputText>
的样式类?
How do I change the style class of
<h:inputText>
when it has a validation error?
在这种情况下,只需检查EL中的 UIInput#isValid()
.当前的UI组件仅可通过隐式EL对象获取 #{component}
.
In that case, just check UIInput#isValid()
in EL. The current UI component is just available by implicit EL object #{component}
.
<h:inputText ... styleClass="#{component.valid ? 'positive' : 'negative'}">
<f:ajax ... render="@this msg" />
</h:inputText>
请注意,我在 render
中添加了 @this
,否则该组件本身将不会被更新.
Note that I added @this
to the render
, otherwise the component itself wouldn't be updated.
您不应使用特定于视图的属性(例如CSS类)来污染模型.您应该尽量将它们放在视图侧.最终将得到更多自然"的解决方案.
You shouldn't be polluting the model with view-specific properties such as CSS classes. You should try to keep them in the view side as much as possible. This will end up in more "natural" solutions.
这篇关于JSF根据验证从bean更新值的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!