我正在尝试在<h:message>
.
这是相关的视图代码:
<h:inputText id="titleId" value="#{bookController.book.title}"/>
<h:message for="titleId"/>
<h:commandButton value="Create a book" actionListener="#{bookController.doCreateBook}" action="listBooks"/>
titleId
当为空时,我需要显示一条消息。当标题为空时,我的@Stateless
EJB 方法会引发异常:
public Book createBook(Book book) throws CustomException {
if(book.getTitle().isEmpty()) {
throw new CustomException("Please, type a Title !");
}
else {
em.persist(book);
return book;
}
}
我的支持 bean 捕获它并设置一条消息:
public void doCreateBook() {
FacesContext ctx = FacesContext.getCurrentInstance();
try {
book = bookEJB.createBook(book);
bookList = bookEJB.findBooks();
} catch (CustomException e) {
ctx.addMessage("titleId", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", e.getMessage()));
}
}
我例外的是,当异常发生时,必须在输入文本标签附近显示错误消息,但事实并非如此,执行显示带有书籍列表的页面和列表下方显示的“错误”消息,如下所示:
如何让完整的异常消息显示在输入字段旁边?