【问题标题】:custom validator call on button through ajax通过ajax自定义验证器调用按钮
【发布时间】:2013-09-09 06:05:53
【问题描述】:

嗨,我编写了一个自定义的验证器,它获取系统名称并将其与数据库中的 id 进行比较,现在我想检查该值是否完全相同,必须允许用户单击按钮并继续前进应该显示一些错误消息。我真的很困惑如何通过ajax调用验证器()。

我的查看页面代码是

<h:commandButton action="sample?faces-redirect=true" value="submit">
                    <f:ajax execute="#{csample.UserValidator}" render="@form" >
                    <h:inputText name="idtext" value="#{csampleBean.id}" />
                    </f:ajax>
                </h:commandButton>

和我的自定义验证器

public void UserValidator(FacesContext context, UIComponent toValidate, Object value)
            throws UnknownHostException, ValidatorException, SQLException, NamingException
    {
        java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
        String machine=  localMachine.getHostName();

        String query = "select * from USER_ where USER_ID = '"+machine+"'";

        Context initContext = new InitialContext();
        Context envContext = (Context)initContext.lookup("java:/comp/env");
         DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
        Connection conn = ds.getConnection();   
        Statement stat = conn.createStatement();
        //get customer data from database
        ResultSet result =  stat.executeQuery(query);

        if (query==machine)
                // what to do here      
            conn.close();

需要一些指导

【问题讨论】:

    标签: ajax jsf validation


    【解决方案1】:

    您需要创建一个实现Validator 接口的类。在验证失败时,只需抛出 ValidatorExceptionFacesMessage。然后,JSF 将注意 FacesMessage 最终出现在与输入组件关联的右侧 &lt;h:message&gt; 中。

    您可以将自定义验证器注册到 JSF,方法是使用 @FacesValidator 注释它,其中包含验证器 ID。您可以在&lt;h:inputXxx validator&gt;&lt;f:validator validatorId&gt; 中引用它。

    这是一个启动示例:

    @FacesValidator("userValidator")
    public class UserValidator implements Validator {
    
        @Override
        public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
            // ...
    
            if (!valid) {
                String message = "Sorry, validation has failed because [...]. Please try again.";
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
            }
        }
    
    }
    

    使用如下(注意:&lt;h:inputText&gt; 没有name 属性!而是使用id;另请注意,您的初始代码 sn-p 有一些没有任何意义的嵌套):

    <h:inputText id="idtext" value="#{csampleBean.id}" validator="userValidator">
        <f:ajax render="idtextMessage" />
    </h:inputText>
    <h:message id="idtextMessage" for="idtext" />
    <h:commandButton action="sample?faces-redirect=true" value="submit" />
    

    另见:


    与具体问题无关,您的 JDBC 代码正在泄漏数据库资源。也请fix

    【讨论】:

      猜你喜欢
      • 2010-12-03
      • 2018-07-30
      • 2017-09-13
      • 1970-01-01
      • 2015-01-08
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多