<h:messages>
標(biāo)簽顯示與UI元素相對(duì)應(yīng)的一個(gè)地方的所有消息。
以下JSF標(biāo)簽 -
<h:messages style="color:red;margin:8px;" />
如果用戶名輸入超過(guò)20個(gè)字符,輸入的密碼小于5個(gè)字符。渲染結(jié)果如下 -
<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>
打開(kāi) NetBeans創(chuàng)建一個(gè)名稱為:Messages 的Web工程,并使用以上代碼。發(fā)布工程,Tomcat啟動(dòng)完成后,在瀏覽器地址欄中輸入以下URL。
http://localhost:8084/Messages
得到以下結(jié)果 -