出现两次的错误消息

问题描述:

我正在学习JSF并需要一些帮助。我正在尝试在页面中执行声明性验证,但呈现的所需消息在HTML标记中出现两次。出现两次的错误消息

在我的托管bean中,我有一个指向学生实体的students字段,它具有以下字段firstNameotherNamessurName

这是Managed Bean的的的样子:

@ViewScoped 
public Class FormController implements Serializeble{ 
private List<Student> students = new ArrayList<>(); 

    @PostConstruct 
    public void init(){ 
    students.add(new Student()); 
    students.add(new Student()); 
    } 

    //getters and setters 
} 

然后在我JSF页面,我有一个ui:repeat指向students在我的豆与输入字段声明确认;

<h:form> 
     <table> 
     <ui:repeat value="#{formController.students}" var="student"> 
     <tr> 
     <td><p:outputLabel value="first name:"/></td> 
     <td><p:inputText value="#{student.firstname}" 
          required="true" 
          requiredMessage="field cannot be blank"/></td> 
     <td><p:messages/></td> 
     </tr> 

     <!--other input fields omitted to make code cleaner--> 

     </ui:repeat> 
     </table> 
     <p:commandButton value="submit" 
         action="#{formController.saveStudents()}"/> 
    </h:form> 

的问题, 我面对于此的是,在像这样的HTML标记每个输入字段产生两次所需的信息:

<span class="bf-message"> 
    <span class="bficon bficon-error-circle-o bf-message-icon" aria-hidden="true</span> 
    <span class="bf-message-detail">this feild cant be left blank</span></span><br /><span class="bf-message"> 
    <span class="bficon bficon-error-circle-o bf-message-icon" aria-hidden="true"></span> 
    <span class="bf-message-detail">this feild cant be left blank</span></span> 


//repeated likewise for all other input field required message,omitted to save space 

这是我的开发环境

  • GlassFish 4.1.1
  • JSF 2.2
  • Primefaaces 6.0
  • NetBeans IDE中。

要添加一些细节,commandButtion操作指向的支持bean方法没有FacesMessages,实体类中的Field也没有验证注释。

的问题是,你嵌套<p:messages />一个<ui:repeat>内。由于ui:repeat迭代了您在渲染响应阶段添加到列表中的所有学生,最终会为每个添加的学生添加一个消息组件。默认情况下,p:messages组件显示添加到FacesContext的所有消息(例如所有验证消息)。

<p:messages />移出<ui:repeat>,消息只显示一次。

另一种解决办法,如果你想成为在inputText右侧显示的消息,将给予inputText组件的id属性,并使用你的<p:messages />这个id属性作为for属性。当然,这个id必须是唯一的。 for属性使messages组件仅显示为此特定组件添加的消息。但这不适用于<ui:repeat>,因为ui:repeat仅多次渲染组件,但实际上并未在组件树中创建多个组件。所以你必须为此使用<c:forEach>。首先请务必阅读this introduction to JSTL tags in JSF

<p:inputText id="#{student.id}" ... /> 
<p:messages for="#{student.id}" /> 
+0

@Kaizen我不太清楚你试图用什么来达到目的。你能详细说明一下吗?噢拍, – jessepeng

+0

,那是另一个问题的错误地方。回到你的身边。如果我想通过你的第二个解决方案,当'ui:repeat'多次渲染相同的组件时,如何在'inputText'上使用'for'属性,但不能在树中创建新组件。我读了这个http://*.com/q/19131583/7646476 – Kaizen

+0

@Kaizen你是对的,我忘记了。我用更正确的信息更新了答案。 – jessepeng