我正在使用JSF(PrimeFaces)/EJB/JPA和MySQL数据库。我想做的是在XHTML正文的顶部显示"用户已成功添加到数据库"信息,当用户成功引入数据库时。我知道我可以使用h:messages,但是,验证错误消息也显示在正文的顶部,我希望错误消息显示在输入字段的下方。我怎么能这么做?
Facelet代码
<h:body>
<h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>`<!--WRONG-->
<p:inputText id="name" required="true" value="#{usersManagedBean.username}" requiredMessage="requiered field">
<f:validator validatorId="validators.NameValidator"/>
</p:inputText>
<p:watermark for="name" value="User" />
<p:message for="name" />
<p:inputText id="age" required="true" value="#{usersManagedBean.username}" requiredMessage="requiered field">
<f:validator validatorId="validators.AgeValidator"/>
</p:inputText>
<p:watermark for="age" value="Age" />
<p:message for="age" />
<p:commandButton value="Save user" action="#{usersManagedBean.saveUser}" ajax="false" />
</h:body>
托管Bean代码
//imports
@Named(value = "usersManagedBean")
@SessionScoped
public class UsersManagedBean implements Serializable
{
String username;
int userage;
@PostConstruct
public void init()
{
username="";
userage=0;
}
//Getters and Setters
public void saveUser()
{
User eUser = new Users();
eUser.setName(username);
eUser.setAge(userage);
ejbUsersDAO.create(eUser); //DAO
addSuccessMessage("User was successfully added to database");
}
public static void addSuccessMessage(String msg)
{
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage("successInfo", facesMsg);
}
}
尝试在<h:messages>
中设置globalOnly="true"
属性,并将addSuccessMessage更改为
fc.addMessage(null, facesMsg);