问题
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:
Navigate to the edit view (edit.xhtml)
post construct called. displaying domain... pre destroy called.
Change the content of the domainDescriptionField input text
nothing logged
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