JSF查看多次重建的Scoped Bean

时间:2013-02-11 12:47:20

标签: jsf java-ee ejb view-scope

我认为@ViewScoped应该阻止在用户位于同一页面时重建bean ...那么为什么我的@ViewScoped JSf控制器bean甚至在动作之前被多次创建处理程序导致浏览器离开该视图?

有人能指出我在正确的方向吗?

这是我的代码:

视图(domain / edit.xhtml)

<h:form prependId="false">
    <h:inputText id="descriptionField" value="#{domainEdit.domain.description}" />
    <h:commandButton id="saveButton" value="save" action="#{domainEdit.save}" />
</h:form>

ViewScoped控制器(DomainEdit.java)

@Named("domainEdit")
@ViewScoped
public class DomainEdit implements Serializable {

    private static final long serialVersionUID = 1L;


    protected DomainEdit() {
    }

    @PostConstruct
    protected void init() {
        System.out.println("post construct called.");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("pre destroy called.");
    }

    public DomainEntity getDomain() {
        System.out.println("displaying domain...");

        // some code to return the domain
        return domain;
    }

    public String save() {
        System.out.println("saving...");

        // some saving code

        return "view";
    }
}

输出

当我部署它并执行以下操作时,我得到以下输出:

  1. 导航至编辑视图(edit.xhtml)

       post construct called.
       displaying domain...
       pre destroy called.
    
  2. 更改domainDescriptionField输入文本的内容

    没有记录

  3. 点击“保存”

  4.   post construct called.
      displaying domain...
      pre destroy called.
    
      post construct called.
      displaying domain...
      pre destroy called.
    
      post construct called.
      displaying domain...
      pre destroy called.
    
      post construct called.
      displaying domain...
      pre destroy called.
    
      post construct called.
      displaying domain...
      saving domain...
      pre destroy called.
    

1 个答案:

答案 0 :(得分:8)

除非您使用的是JSF 2.2(目前尚未提供)或MyFaces CODI(我预计您会明确提及),@ViewScoped不起作用CDI。这也非常符合您的问题症状。

通过JSF而不是CDI管理bean。从@Named("domainEdit")包中@ManagedBean替换javax.faces.bean。或者,安装MyFaces CODI以将JSF @ViewScoped连接到CDI。