JSF View Scoped Bean Reconstructed Multiple Times [duplicate]

巧了我就是萌 提交于 2019-12-17 19:54:45

问题


I thought @ViewScoped was supposed to prevent the bean from being reconstructed while the user is on the same page... So why is my @ViewScoped JSf controller bean being created multiple times even before the action handler causes the browser to navigate away from that view?

Can anyone point me in the right direction here?

Here is my code:

The View (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>

The ViewScoped controller (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";
    }
}

Output

I get the following output when I deploy this and perform the following:

  1. Navigate to the edit view (edit.xhtml)

       post construct called.
       displaying domain...
       pre destroy called.
    
  2. Change the content of the domainDescriptionField input text

    nothing logged

  3. Click 'save'

  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:


Unless you're using JSF 2.2 (which is still not out yet at this moment) or MyFaces CODI (which I'd have expected that you would explicitly mention that), the @ViewScoped doesn't work in CDI. This also pretty much matches your problem symptoms.

Manage the bean by JSF instead of CDI. Replace @Named("domainEdit") by @ManagedBean from javax.faces.bean package. Or, install MyFaces CODI to bridge JSF @ViewScoped to CDI.



来源:https://stackoverflow.com/questions/14812238/jsf-view-scoped-bean-reconstructed-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!