EL 3.0:使用Spring托管bean将Class中的常量添加到ELContext

时间:2013-11-26 11:17:21

标签: java spring jsf el jsf-2.2

我尝试使用JSF 2.2。,EL 3.0 ..

为我的网络应用程序设置容器

关于这篇文章in stackoverflow,可以用EL 3.0做到这一点。那样:

@ManagedBean(eager=true)
@ApplicationScoped
public class Config {

    @PostConstruct
    public void init() {
       FacesContext.getCurrentInstance().getApplication().addELContextListener(new ELContextListener() {
          @Override
          public void contextCreated(ELContextEvent event) {  
             event.getELContext().getImportHandler().importClass("com.example.YourConstants");
         }
       });
    }
}

如果bean不是由jsf管理的,那么有没有例子可以解决这个问题?

1 个答案:

答案 0 :(得分:1)

看看Omnifaces importConstants。它应该为你做所有的工作。

http://showcase.omnifaces.org/taghandlers/importConstants

取自omnifaces的例子......

Managed Bean

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import org.omnifaces.showcase.model.ExampleEnum;

@ManagedBean
@RequestScoped
public class ConstantsBean {

    public static final String CONSTANT1 = "Constant one";
    public static final String CONSTANT2 = "Constant two";

    private ExampleEnum exampleEnum;

    public ExampleEnum getExampleEnum() {
        return exampleEnum;
    }

    public void setExampleEnum(ExampleEnum exampleEnum) {
        this.exampleEnum = exampleEnum;
    }

}

ExampleEnum

public enum ExampleEnum {

    ONE, TWO, THREE;

    public String getFriendlyName() {
        return name().charAt(0) + name().substring(1).toLowerCase();
    }

}

XHTML中的示例用法

<o:importConstants type="org.omnifaces.showcase.taghandlers.ConstantsBean" />
<o:importConstants type="org.omnifaces.showcase.model.ExampleEnum" />

<h3>All constants of <code>ConstantsBean</code></h3>
<ul>
    <li>#{ConstantsBean.CONSTANT1}</li>
    <li>#{ConstantsBean.CONSTANT2}</li>
</ul>

<hr />

<h3>All values of <code>ExampleEnum</code></h3>
<ul>
    <li>#{ExampleEnum.ONE}</li>
    <li>#{ExampleEnum.TWO}</li>
    <li>#{ExampleEnum.THREE}</li>
</ul>