我从数据库加载了数据,当单击命令按钮时:
<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));
}
...
它加载文章和评论。此外,文本区域和命令按钮也在同一页面上呈现,用于添加注释。
<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
。
更改
actionListener="#{persistenceBean.saveComment}"
自
actionListener="#{dataBean.saveComment}"
并在DataBean
中注入PersistenceBean
(通过@EJB
,我假设?),以便您可以在DataBean#saveComment()
执行以下操作:
persistenceBean.saveComment(e);
loadCurrentArticle();
与具体问题无关,在 JSF 2.x 中传递属性有更优雅的方法。另请参阅如何将所选行传递到数据表中的命令链接?