JSF <h:messages>標籤

<h:messages>標籤顯示與UI元素相對應的一個地方的所有消息。
以下JSF標籤 -

<h:messages style="color:red;margin:8px;" />

如果用戶名輸入超過20個字符,輸入的密碼小於5個字符。渲染結果如下 -

<ul style="color:red;margin:8px;">
   <li>  UserName: Validation Error: 
   Length is greater than allowable maximum of '20' </li>
   <li>  Password: Validation Error: 
   Length is less than allowable minimum of '5' </li>
</ul>

實例

以下是文件:index.xhtml 中的代碼 -

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      >

    <h:body>
    <h:form>
      <h:messages style="color:red;margin:8px;" />
      <br />
      <h:panelGrid columns="3">
        Enter your username :
        <h:inputText id="username" value="#{user.username}" 
          size="20" required="true"
          label="UserName" >
          <f:validateLength minimum="5" maximum="10" />
        </h:inputText>

        <h:message for="username" style="color:red" />

        Enter your age :
        <h:inputText id="age" value="#{user.age}" 
          size="20" required="true"
          label="Age" >
          <f:validateLongRange for="age" minimum="1" maximum="200" />
        </h:inputText>

        <h:message for="age" style="color:red" />

      </h:panelGrid>

      <h:commandButton value="Submit" action="result" />

    </h:form>

    </h:body>
</html>

以下是文件:UserBean.java 中的代碼 -

package com.yiibai;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="user")
@SessionScoped
public class UserBean implements Serializable{

  private static final long serialVersionUID = 1L;

  public String username;
  public int age;

  public String getUsername() {
    return username;
  }
  public void setUsername(String username) {
    this.username = username;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }

}

以下是文件:result.xhtml 中的代碼 -

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      >

    <h:body>

    Username : #{user.username}

    <br />

    Age : #{user.age}

    </h:body>
</html>

運行測試

打開 NetBeans創建一個名稱爲:Messages 的Web工程,並使用以上代碼。發佈工程,Tomcat啓動完成後,在瀏覽器地址欄中輸入以下URL。

http://localhost:8084/Messages

得到以下結果 -

JSF