JSF验证模板中没有问题

时间:2013-04-17 15:55:35

标签: jsf jsf-2 facelets

JSF验证不起作用当我提交时,我在myfaces(2.1.10)和mojarra(2.1.21)下尝试过,结果相同。我的代码也是如此。理论上不执行onSubmit()并显示错误消息在m_name.But实际上是执行onSubmit()而不显示错误消息。

的template.xhtml

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:rich="http://richfaces.org/rich">
<h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="Cache-Control" content="no-cache" />
    <title>Title</title>
</h:head>
<h:body>
        <ui:insert name="body"></ui:insert>
</h:body>
</html>

模板客户端文件templatevalidation.xhtml

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    template="/template.xhtml">
    <ui:define name="body">
        <h:form>
            <div>
                <h:inputText id="name" value="#{templateBean.name}">
                    <f:validateRequired />
                    <f:validateLength minimum="5" />
                </h:inputText>
                <h:message id="m_name" for="name" />
            </div>
            <div>
                <h:commandButton action="#{templateBean.onSubmit}" value="submit">
                    <f:ajax execute="name" render="m_name" />
                </h:commandButton>
            </div>
        </h:form>
    </ui:define>
</ui:composition>

这是我的bean TemplateBean.class

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean
@ViewScoped
public class TemplateBean implements Serializable{

    private static final long serialVersionUID = 9009393522101806766L;

    private String name;

    public void onSubmit(){
        System.out.println("Name: " + name);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


}

2 个答案:

答案 0 :(得分:0)

您需要在AJAX调用后更新<h:message>组件,以使用render标记中的<f:ajax>属性显示错误消息:

<h:message id="nameMsg" for="name" />

<h:commandButton action="#{templateBean.onSubmit}" value="submit">
    <f:ajax execute="name" render="nameMsg" />
</h:commandButton>

答案 1 :(得分:-1)

必须使用hibernate-validation

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.0.0.Final</version>
</dependency>