JSF:通过字段从Validator访问Bean [英] JSF: Accessing Bean from Validator via field
问题描述
我有一个JSF验证程序,用于检查容器编号字符串是否符合 ISO-6346 specficiation。
I have a JSF validator that checks whether a Container Number string conforms to the ISO-6346 specficiation.
它工作正常,但我需要根据容器编号来自Bean的其他值添加一些条件处理。这个Bean可以有几种不同的类型。
It works fine, however I need to add some conditional processing in based on other values in the Bean where the Container Number comes from. This Bean can be of several different types.
有没有办法在验证器中访问Bean并对其执行操作?理想情况下,我希望将其作为验证器,但如果没有解决方案,我必须在持久化之前在Bean中实现逻辑。
Is there any way to access the Bean in the validator and perform operations on it? Ideally I'd love to keep it as a validator, however if there is no solution I'll have to implement the logic in the Bean before persisting.
我是按照以下方式思考:
I'm thinking something along the lines of:
public class ContainerNumberValidator implements javax.faces.validator.Validator {
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
Object bean = UIComponent.getMyBeanSomehowThroughAMagicMethod();
if(bean instanceof BeanA) {
//do this
} else if(bean instanceof BeanB) {
//do that
}
}
UPDATE:在很多方面,这与验证的问题类似多个字段同时。 BalusC的此代码非常有用。
UPDATE: In many ways this is a similar problem to the validation of multiple fields at the same time. This code by BalusC is helpful.
非常感谢。
D。
推荐答案
使用< f:attribute>
,您可以将Bean传递给验证器,并将其作为值表达式从组件中检索。
Using the <f:attribute>
you can pass a Bean to the validator and retrieve it from the component as a value expression.
所以我的输入是这样的(必须使用< f:validator>
而不是<$ c上的验证器属性$ c>< h:inputText> ):
So my input is like this (must be using <f:validator>
and not the validator attribute on the <h:inputText>
) :
<h:inputText id="containerNum" size="20" maxlength="20" value="#{containerStockAction.containerStock.containerNumber}">
<f:validator validatorId="containerNumberValidator" />
<f:attribute name="containerBean" value="#{containerStockAction.containerStock}"/>
</h:inputText>
我的验证员类:
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
String containerNumber = (String)value;
Object containerBean = component.getValueExpression("containerBean").getValue(context.getELContext());
if(containerBean instanceof BeanA) {
//do this
}
这篇关于JSF:通过字段从Validator访问Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!