-1

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

模板.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;
    }


}
4

2 回答 2

0

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

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

<h:commandButton action="#{templateBean.onSubmit}" value="submit">
    <f:ajax execute="name" render="nameMsg" />
</h:commandButton>
于 2013-04-17T22:59:23.960 回答
-1

必须使用休眠验证

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.0.0.Final</version>
</dependency>
于 2013-04-22T10:19:32.387 回答