Java 将枚举值作为参数从 JSF 传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3916871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:51:13  来源:igfitidea点击:

Passing a Enum value as a parameter from JSF

javajsfenumsel

提问by Thang Pham

I am trying to migrate my existing code to using Enum and I run into some problems due to my lack experience with Enum. First of all here is my structures. In my EJB, alongs with Entity, I have a enum class (not sure if it even a class).

我正在尝试将现有代码迁移到使用 Enum,但由于缺乏 Enum 经验,我遇到了一些问题。首先这里是我的结构。在我的EJB, 和 Entity 中,我有一个 enum 类(不确定它是否是一个类)。

public enum Type {
    PROFILE_COMMENT,
    GROUP_COMMENT
} 

At my managed bean myBean.java, I have

在我的托管 bean 中myBean.java,我有

@ManagedBean(name="myBean")
@SessionScoped
public class myBean {

    private Type type;

    public myBean() {
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public void Test(Type t){
        System.out.println(t);
    }

}

then at my JSF,

然后在我的 JSF,

<h:commandButton value="Test" action="#{myBean.Test(myBean.type.PROFILE_COMMENT)}" />

I got java.lang.ClassNotFoundException:saying Typeis not a class

java.lang.ClassNotFoundException:Type不是一个班级

The reason I have Typein my EJB so that I can create an enumerated type for my Entity, so my query would look like this

Type在 EJB 中的原因是为了我可以为我的实体创建一个枚举类型,所以我的查询看起来像这样

select c from X c where c.type = Type.PROFILE_COMMENT

采纳答案by BalusC

You can't access enums like that in EL. JSF has however builtin enum converters for EL. You can just use the enum name as string.

您无法在 EL 中访问这样的枚举。然而,JSF 为 EL 内置了枚举转换器。您可以只使用枚举名称作为字符串。

<h:commandButton value="Test" action="#{myBean.Test('PROFILE_COMMENT')}" />

回答by ziodraw

In my case thathelped me.

就我而言,这对我帮助。

Simple compare enum to its value. EL recognize it and also check if that value exists while validating xhtml.

简单地将枚举与其值进行比较。EL 识别它并在验证 xhtml 时检查该值是否存在。

<c:if test="#{requestManager.selectedRequestType == 'ItemCreate' or requestManager.selectedRequestType == 'ItemChange'}"></c:if>