这里主要介绍一下如何在PrimeFaces中实现错误提示

官方参考文档如下:

https://www.primefaces.org/showcase/ui/message/messages.xhtml?jfwid=96ee4

https://primefaces.github.io/primefaces/10_0_0/#/components/messages

由于PrimeFaces有注释Bug,这里先介绍贴出一段带注释的代码作为参考

<?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:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head></h:head>
<h:body style="margin-left:50px">
<div class="card">
<!-- 定义一个变量名 -->
<c:set var="msg" value="#{messages}"/>
<h:form>
<h1>Validation</h1>
<h:panelGrid id="grid" columns="3" cellpadding="7">
<!-- 文本输入框 -->
<p:inputText id="input" value="#{msg.quality}">
<!-- 当元素失去焦点时发生 blur 事件,更新m1的值,添加error为监听事件 -->
<p:ajax event="blur" update="m1" listener="#{msg.error(msg.quality)}"/>
</p:inputText>
<!-- 报错的文本提示框,关联文本输入框 -->
<p:messages id="m1" for="input" display="input" showDetail="true"/>
</h:panelGrid>
<p:commandButton id="submitButton" value="Submit" update="grid" styleClass="p-mt-3"/>
</h:form>
</div>
</h:body>
</html>

完整代码如下:

messages.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:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head></h:head>
<h:body style="margin-left:50px">
<div class="card">
<c:set var="msg" value="#{messages}"/>
<h:form>
<h1>Validation</h1>
<h:panelGrid id="grid" columns="3" cellpadding="7">
<p:inputText id="input" value="#{msg.quality}">
<p:ajax event="blur" update="m1" listener="#{msg.error(msg.quality)}"/>
</p:inputText>
<p:messages id="m1" for="input" display="input" showDetail="true"/>
</h:panelGrid>
<p:commandButton id="submitButton" value="Submit" update="grid" styleClass="p-mt-3"/>
</h:form>
</div>
</h:body>
</html>

MessagesView.java

package com.daniel.model.menu;


import lombok.Getter;
import lombok.Setter;

import javax.faces.application.FacesMessage;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;

/**
* @Author Daniel
* @Description primefaces 错误提示
**/
@Named(value = "messages")
@RequestScoped
public class MessagesView {
@Getter
@Setter
private int quality = 0;

// 如果输入的值大于5,就给出提示信息
public void error(int quality) {
int max = 5;
if (quality > max) {
/*
addMessage(前端要显示标签的id,(错误级别,错误显示的文本标题,错误显示的文本内容))
*/
FacesContext.getCurrentInstance().addMessage("input", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Message Content"));
}
}

}

默认访问URL:http://localhost:8080/messages.xhtml

效果展示:

PrimeFaces Error Messages实现_PrimeFaces

附:环境搭建与lombok依赖

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>