单击命令按钮时,我从DB加载了数据:
<h:commandButton value="Show article content and comments" action="#{dataBean.activateArticleContentView}" actionListener="#{dataBean.loadCurrentArticle}">
<f:attribute name="articleId" value="#{article.id}"></f:attribute>
</h:commandButton>
@ManagedBean
@ViewScoped
public class DataBean implements Serializable {
...
private List<UserAcc> users;
private List<Article> articles;
private List<ArticleComment> articleComments;
private Article currentArticle;
public void loadComments(ActionEvent e) {
DataBaseUtil dbu = new DataBaseUtil();
int articleId = (Integer) e.getComponent().getAttributes()
.get("articleId");
articleComments = dbu.loadArticleComments(articleId);
}
public void loadCurrentArticle(ActionEvent e) {
DataBaseUtil dbu = new DataBaseUtil();
int articleId = (Integer) e.getComponent().getAttributes()
.get("articleId");
this.currentArticle = dbu.loadArticleById(articleId);
this.currentArticle.setComments(dbu.loadArticleComments(articleId));
}
...
它加载文章及其评论。 textArea和commandButton也在同一页面上呈现,用于添加注释。
<h:inputTextarea value="#{persistenceBean.text}" style="height: 50px; width: 300px">
</h:inputTextarea>
<h:commandButton value="Save" actionListener="#{persistenceBean.saveComment}">
<f:attribute name="userName" value="#{loginBean.name}"></f:attribute>
<f:attribute name="articleId" value="#{dataBean.currentArticle.id}"></f:attribute>
</h:commandButton>
命令按钮在另一个bean(PersistenceBean)中激活此方法:
public void saveComment(ActionEvent e){
int articleId = (Integer) e.getComponent().getAttributes().get("articleId");
String userName = (String) e.getComponent().getAttributes().get("userName");
DataBaseUtil dbu = new DataBaseUtil();
UserAcc user = dbu.loadUserByName(userName);
ArticleComment comment = new ArticleComment();
comment.setText(this.text);
Date postat = new Date();
comment.setPostat(postat.toString());
dbu.saveComment(articleId, user.getId(), comment);
}
我的问题是如何使用注释重新呈现表,以便可以立即显示更改。现在我需要回到文章视图,然后单击显示文章内容和注释的按钮。我可以为添加注释的按钮设置多个动作侦听器,换句话说,如何在添加注释后再次使用dataBean.loadCurrentArticle
。
答案 0 :(得分:0)
更改
actionListener="#{persistenceBean.saveComment}"
到
actionListener="#{dataBean.saveComment}"
并在PersistenceBean
中注入DataBean
(我假设是@EJB
),以便您可以在DataBean#saveComment()
中执行以下操作:
persistenceBean.saveComment(e);
loadCurrentArticle();
无关具体问题,有更优雅的方式来传递JSF 2.x中的属性。另请参阅How can I pass selected row to commandLink inside dataTable?