【问题标题】:How to use abstract class as CDI managed bean in JSF view如何在 JSF 视图中使用抽象类作为 CDI 托管 bean
【发布时间】:2015-04-16 21:32:11
【问题描述】:

我可以在 JSF 视图中使用抽象类作为 CDI 托管 bean 吗?我想在派生类中设置或覆盖属性,并在父抽象类的 JSF 页面中使用它。派生视图设置模板父视图必须显示为所有子视图的公共部分的上下文。 我听说我可以在 JSF 视图中使用带有 @Named 注释的抽象类,但是我得到了错误

目标不可达,标识符“viewModel”解析为空

如果我将抽象类更改为典型类,那么它的工作。在 JSF 视图中使用抽象类可能是不可能的吗?

ViewModel.java

@Named
@ConversationScoped
@Inherited
@Documented
@Stereotype
@Target({ TYPE })
@Retention(RUNTIME)
public abstract class ViewModel {
    private String foo;

    public void setFoo(String foo) {
        this.foo = foo;
    }

    public String getFoo() {
        return foo;
    }

    abstract void bar();
}

DerivedViewModel.java

@Named
@ConversationScoped
@Inherited
@Documented
@Stereotype
@Target({ TYPE })
@Retention(RUNTIME)
public class DerivedViewModel extends ViewModel {
    public void init() {
        this.setFoo("Foo");
    }

    @Override
    void bar() {;}
}

View.xhtml

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
    xmlns:fn="http://xmlns.jcp.org/jsp/jstl/functions" xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"
    xmlns:p="http://primefaces.org/ui" xmlns:pe="http://primefaces.org/ui/extensions"
    xmlns:sys="http://argustelecom.ru/system" xmlns:o="http://omnifaces.org/ui">

    <ui:param name="viewModel" value="#{viewModel}" />

    <ui:define name="body">
        <h:outputText value="#{viewModel.foo}" />

        <ui:insert name="derived" />
    </ui:define>

</ui:composition>

DerivedView.xhtml

<ui:composition template="View.xhtml" xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
    xmlns:fn="http://xmlns.jcp.org/jsp/jstl/functions" xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"
    xmlns:p="http://primefaces.org/ui" xmlns:pe="http://primefaces.org/ui/extensions"
    xmlns:sys="http://argustelecom.ru/system" xmlns:o="http://omnifaces.org/ui">

    <ui:param name="viewModel" value="#{derivedViewModel}" />
    <ui:define name="metadata">
        <f:metadata>
            <f:viewAction action="#{derivedViewModel.init()}"/>
        </f:metadata>
    </ui:define>

    <ui:define name="derived">
        blablabla
    </ui:define>

</ui:composition>

【问题讨论】:

    标签: jsf jsf-2 abstract-class cdi


    【解决方案1】:

    忘记 EL 或 JSF。从 OO 的角度思考。你能打这个电话吗?

    viewModel.foo
    

    答案是否定的,因为它是abstract,而viewModel 不能作为abstractViewModel 的实例存在。出于完全相同的原因,您不能在 EL 中使用它。

    【讨论】:

      猜你喜欢
      • 2013-08-20
      • 2016-07-09
      • 2015-04-20
      • 2011-12-05
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 2023-03-07
      相关资源
      最近更新 更多