加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 无法将JSF ViewScoped bean注入Validator作为ManagedPro

发布时间:2020-12-14 05:34:14 所属栏目:Java 来源:网络整理
导读:我试图将JSF ViewScoped bean作为ManagedProperty注入到实现 javax.faces.validator.Validator的RequestScoped bean中.但是始终会注入ViewScoped bean的新副本. ViewScoped Bean @ViewScoped@ManagedBeanpublic class Bean { private Integer count = 1; pri
我试图将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,那么同样的情况也是如此.另外,如果我删除了Validator实现的RequestScoped bean并在PostConstruct中使用了一个记录器,那么计数会根据预期为每个ajax请求递增.

我做错了吗?还是这应该怎么工作?提前致谢

解决方法

那是因为< f:validator>的绑定属性在视图构建期间进行评估.在这一刻,视图范围还不可用(它是有意义的,它仍然在繁忙的建立…),所以将创建一个全新的视图范围的bean,然后与请求作用域bean具有相同的效果.在即将到来的JSF 2.2中,这个鸡蛋问题将得到解决.

在此之前,如果您绝对有兴趣,请在validate()方法中需要一个视图范围的bean(我宁愿查找其他方式,例如< f:attribute>,EJBs,多字段验证器等)那么唯一的方法就是在validate()方法本身中以编程方式评估#{bean},而不是通过@ManagedProperty注入它.

您可以使用Application#evaluateExpressionGet()

Bean bean = context.getApplication().evaluateExpressionGet(context,"#{bean}",Bean.class);

也可以看看:

> JSTL in JSF2 Facelets… makes sense? – 更好地了解“查看构建时间”与“查看渲染时间”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读