【问题标题】:JSF rerender data loaded from DBJSF 重新渲染从数据库加载的数据
【发布时间】:2011-08-22 14:30:58
【问题描述】:

点击命令按钮时,我从数据库加载了数据:

<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));
    }
...

它会加载文章,它是 cmets。还在同一页面上呈现 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);
    }

我的问题是如何使用 cmets 重新渲染表格,以便可以立即显示更改。现在我需要回到文章视图并单击显示文章内容和 cmets 的按钮。我可以为添加评论的按钮设置多个动作监听器,换句话说,添加评论后如何再次使用dataBean.loadCurrentArticle

【问题讨论】:

    标签: hibernate jsf


    【解决方案1】:

    改变

    actionListener="#{persistenceBean.saveComment}"
    

    actionListener="#{dataBean.saveComment}"
    

    并在DataBean 中注入PersistenceBean(我假设是@EJB?),以便您可以在DataBean#saveComment() 中执行以下操作:

    persistenceBean.saveComment(e);
    loadCurrentArticle();
    

    与具体问题无关,在 JSF 2.x 中有更优雅的方式来传递属性。另见How can I pass selected row to commandLink inside dataTable?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-15
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 2014-08-27
      • 2023-01-07
      • 2021-05-03
      相关资源
      最近更新 更多