我正在尝试将 JSF ViewScoped bean 作为 ManagedProperty 注入到实现 javax.faces.validator.Validator 的 RequestScoped bean 中。但是总是注入一个新的 ViewScoped bean 副本。
ViewScoped Bean
@ViewScoped
@ManagedBean
public class Bean {
private Integer count = 1;
private String field2;
public String action(){
++count;
return null;
}
public String anotherAction(){
return null;
}
//getter and setter
}
验证器
@RequestScoped
@ManagedBean
public class SomeValidator implements Validator {
public void validate(FacesContext context, UIComponent comp, Object value)
throws ValidatorException {
//logging bean.getCount() is always one here. Even after calling ajax action a few times
}
@ManagedProperty(value = "#{bean}")
private Bean bean;
}
xhtml页面
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
</h:head>
<h:body>
<h:form>
<h:panelGroup layout="block" id="panel1">
<h:commandButton type="submit" value="Action" action="#{bean.action}">
<f:ajax render="panel1"></f:ajax>
</h:commandButton>
<h:outputText value="#{bean.count}"></h:outputText>
</h:panelGroup>
<h:panelGroup layout="block" id="panel2">
<h:inputText type="text" value="#{bean.field1}">
<f:validator binding="#{someValidator}" />
</h:inputText>
</h:panelGroup>
<h:commandButton type="submit" value="Another Action" action="#{bean.anotherAction}">
<f:ajax execute="panel2" render="panel2"></f:ajax>
</h:commandButton>
</h:form>
</h:body>
</html>
正如代码中提到的,即使在调用 ajax 操作几次之后,当记录 bean.getCount() 时总是显示一个。
但是,如果我将 ViewScoped 更改为 SessionScoped,同样的情况也适用。此外,如果我删除 RequestScoped bean 的 Validator 实现并在 PostConstruct 中使用记录器,则每个 ajax 请求的计数都会按预期增加。
难道我做错了什么?或者这应该如何工作?提前致谢