Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JSF在转换前保存输入值_Jsf_Converter_State - Fatal编程技术网

JSF在转换前保存输入值

JSF在转换前保存输入值,jsf,converter,state,Jsf,Converter,State,我有一个输入字段,用户在其中输入他们的社会保险号(userid)。这个数字必须采用特定的格式,所以我使用自定义转换器来正确格式化它。稍后,将根据DB检查该数字。 当检查失败时,我希望数字以用户出于UX原因输入的方式显示。但是转换是在检查之前进行的,并且支持bean中的userid被设置为转换后的值,原始数字丢失。保存原始值的最佳方法是什么 <h:inputText id="userId" value="#{bean.userId}"> <f:converter conv

我有一个输入字段,用户在其中输入他们的社会保险号(userid)。这个数字必须采用特定的格式,所以我使用自定义转换器来正确格式化它。稍后,将根据DB检查该数字。 当检查失败时,我希望数字以用户出于UX原因输入的方式显示。但是转换是在检查之前进行的,并且支持bean中的userid被设置为转换后的值,原始数字丢失。保存原始值的最佳方法是什么

<h:inputText id="userId" value="#{bean.userId}">
    <f:converter converterId="IdConverter" />
</h:inputText>

如果我正确理解了您的问题,则无需保存原始值。利用JSF生命周期

除了自定义转换器外,还需要自定义验证器。在验证器中,如果转换后的输入与数据库上的数据之间的检查成功,则自定义转换器的
getAsString
将简单地返回转换后的输入。但是,如果转换成功但验证失败(意味着对db记录的检查不成功),那么您只需抛出一个错误。将不会调用
getAsString
,并显示原始输入

关于如何实现这一目标,我可以想到两种方法。对于第一种方法,您可以在bean中定义一个验证器方法,并在该方法中移动验证逻辑。例如:

public class Bean {    
    //Remainder omitted

    public void validate(FacesContext fc, UIComponent uic, Object o) {
        //Get the converted input. Assuming of type String
         String convertedInput = (String) o; 

        //Move the db check in this method. If it fails simply throw 
        //a ValidatorException like below. If it succeeds, don't return anything

        //throw new ValidatorException(new FacesMessage("Validation Failed")); 
    }
} 
注意返回类型和参数

然后您将在
中添加
验证器
属性,如下所示

<h:inputText id="userId" value="#{bean.userId}" validator="#{bean.validate}">
然后添加您的


您的问题似乎表明您对JSF生命周期缺乏了解。我强烈建议你花时间尽可能多地理解这个概念。您可能无法一下子理解它,但随着您对JSF的深入了解,某些方面会变得更加清晰。这是一个好的开始


在验证器中,在UI组件上使用getValue,如下所示。。。。对象oldValue=((UIInput)uiComponent.getValue();你的意思是在我的转换器中吗?如果是,我如何返回转换后的值和旧值?
@FacesValidator("customValidator")
public class MyValidator implements javax.faces.validator.Validator {

    @Override
    public void validate(FacesContext fc, UIComponent uic, Object o) {
        //Same logic as bean validator method
    }
}
<f:validator validatorId="customValidator" />