如何使用 EL 表达式中的键获取 EnumMap 中的值?

发布于 2024-11-27 15:56:02 字数 398 浏览 0 评论 0原文

我有一个 EnumMap:

EnumMap<Gender, Integer> genderMap = new EnumMap(Gender.class);

其中 Gender 是 public enum Gender {Male, Female};

我有 req.setAttribute("genderMap", sexMap);

现在我想得到通过 JSP 文件中的键获取 genderMap 中的值:

${genderMap['Male']}

但这不会获取 genderMap 中的值。为什么?

I have a EnumMap:

EnumMap<Gender, Integer> genderMap = new EnumMap(Gender.class);

where Gender is public enum Gender {Male, Female};

And I have req.setAttribute("genderMap", genderMap);

Now I want to get the value from genderMap by a key in JSP file:

${genderMap['Male']}

but this doesn't get the value in genderMap. Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

ゞ记忆︶ㄣ 2024-12-04 15:56:02

不要使用枚举映射。只需将枚举用作 Java 中的枚举和 JSP/EL 中的字符串即可。

我假设您因为数据库映射而需要该整数。例如,Male 在数据库中存储为1Female 在数据库中存储为0。在这种情况下,您需要按如下方式重新设计枚举:

public enum Gender {

    Male(1), Female(0);

    private int id;

    private Gender(int id) { 
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public static Gender valueOf(int id) {
        for (Gender gender : values()) {
            if (gender.id == id) {
                return gender;
            }
        }

        return null;
    }

}

当通过 JDBC 从数据库填充 Person 时,只需执行

person.setGender(Gender.valueOf(resultSet.getInt("gender")));

在 JSP 中向最终用户显示预选选项时,只需执行

request.setAttribute("genders", Gender.values());

Gender:<br/>
<c:forEach items="${genders}" var="gender">
    <input type="radio" id="gender_${gender.id}" name="gender" value="${gender.id}" 
        ${gender == person.gender ? 'checked="checked"' : ''} />
    <label for="gender_${gender.id}">${gender}</label>
    <br />
</c:forEach>

什至不执行 id

Gender:<br/>
<c:forEach items="${genders}" var="gender">
    <input type="radio" id="gender_${gender}" name="gender" value="${gender}" 
        ${gender == person.gender ? 'checked="checked"' : ''} />
    <label for="gender_${gender}">${gender}</label>
    <br />
</c:forEach>

在 servlet 中收集提交的值时,只需

Gender gender = Gender.valueOf(Integer.valueOf(request.getParameter("gender")));

在 HTML 中不使用 id 时执行 或 即可

Gender gender = Gender.valueOf(request.getParameter("gender"));

Don't use enum mappings. Just use enums as enums in Java and as strings in JSP/EL.

I'll assume that you need that integer because of a database mapping. E.g. Male is stored as 1 in database and Female is stored as 0 in database. In that case, you need to redesign your enum as follows:

public enum Gender {

    Male(1), Female(0);

    private int id;

    private Gender(int id) { 
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public static Gender valueOf(int id) {
        for (Gender gender : values()) {
            if (gender.id == id) {
                return gender;
            }
        }

        return null;
    }

}

When populating the Person from DB by JDBC, just do

person.setGender(Gender.valueOf(resultSet.getInt("gender")));

When showing preselected options to enduser in JSP, just do

request.setAttribute("genders", Gender.values());

and

Gender:<br/>
<c:forEach items="${genders}" var="gender">
    <input type="radio" id="gender_${gender.id}" name="gender" value="${gender.id}" 
        ${gender == person.gender ? 'checked="checked"' : ''} />
    <label for="gender_${gender.id}">${gender}</label>
    <br />
</c:forEach>

or even without the id

Gender:<br/>
<c:forEach items="${genders}" var="gender">
    <input type="radio" id="gender_${gender}" name="gender" value="${gender}" 
        ${gender == person.gender ? 'checked="checked"' : ''} />
    <label for="gender_${gender}">${gender}</label>
    <br />
</c:forEach>

When collecting submitted values in servlet, just do

Gender gender = Gender.valueOf(Integer.valueOf(request.getParameter("gender")));

or when using without id in HTML

Gender gender = Gender.valueOf(request.getParameter("gender"));
叫思念不要吵 2024-12-04 15:56:02

因为 'Male' 计算结果为字符串“Male”,而不是 Gender.Male。您需要有权访问 Gender.Male 常量才能访问其映射条目。但在 JSP EL 中访问常量是不可能的,因此您可能需要这样做:

req.setAttribute("male", Gender.Male);
req.setAttribute("genderMap", genderMap);

...

${genderMap[male]}

Because 'Male' evaluates to the String "Male", not to Gender.Male. You would need to have access to the Gender.Male constant to access its map entry. But accessing constants is not possible in JSP EL, so you might want to do :

req.setAttribute("male", Gender.Male);
req.setAttribute("genderMap", genderMap);

...

${genderMap[male]}
远昼 2024-12-04 15:56:02
Map<Gender, Integer> genderMap = new HashMap<Gender, Integer>();

${genderMap['Male']}

这肯定会起作用。

Map<Gender, Integer> genderMap = new HashMap<Gender, Integer>();

and

${genderMap['Male']}

this would work definitely.

江南月 2024-12-04 15:56:02

我的解决方案是为枚举映射创建一个包装器(适配器)。它需要 String 键并通过调用 Enum.valueOf() 方法将它们转换为相应的 Enum 值。

示例 bean 中的相关部分:

private Map <Action, Permission> permissions = new EnumMap<>(Action.class);

/** For java access */
public Map<Action, Permission> getPermissions() {
    return permissions;
}

/** For EL access */
public Map<String, Permission> getPermissionsAsString() {
    return new EnumMapWrapper<>(Action.class, permissions);
}

现在我可以方便地访问 EL 中的映射元素:

#{rule.permissionsAsString['MODIFY']}

这是包装类:

public class EnumMapWrapper<K extends String, V> implements Map<K, V> {

    private Map<Enum, V> map;
    private Class<? extends Enum> enumType;

    public EnumMapWrapper(Class<? extends Enum> enumType, Map<? extends Enum, V> map) {
        this.enumType = enumType;
        this.map = (Map<Enum, V>)map;
    }

    private Enum valueOf(Object key) {
        if (!(key instanceof String)) {
            throw new IllegalArgumentException("Only string keys are permitted");
        }

        return Enum.valueOf(enumType, (String)key);
    }

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean containsKey(Object key) {
        return map.containsKey(valueOf(key));
    }

    @Override
    public boolean containsValue(Object value) {
        return map.containsValue(value);
    }

    @Override
    public V get(Object key) {
        return map.get(valueOf(key));
    }

    @Override
    public V put(K key, V value) {
        return map.put(valueOf(key), value);
    }

    @Override
    public V remove(Object key) {
        return map.remove(valueOf(key));
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void clear() {
        map.clear();
    }

    @Override
    public Set<K> keySet() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Collection<V> values() {
        return map.values();
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        throw new UnsupportedOperationException();
    }
}

My solution was to create a wrapper (adapter) for enum maps. It expects String keys and converts them to corresponding Enum values by calling Enum.valueOf() method.

Relevant parts from an example bean:

private Map <Action, Permission> permissions = new EnumMap<>(Action.class);

/** For java access */
public Map<Action, Permission> getPermissions() {
    return permissions;
}

/** For EL access */
public Map<String, Permission> getPermissionsAsString() {
    return new EnumMapWrapper<>(Action.class, permissions);
}

Now I can conveniently access the map elements in EL:

#{rule.permissionsAsString['MODIFY']}

Here's the wrapper class:

public class EnumMapWrapper<K extends String, V> implements Map<K, V> {

    private Map<Enum, V> map;
    private Class<? extends Enum> enumType;

    public EnumMapWrapper(Class<? extends Enum> enumType, Map<? extends Enum, V> map) {
        this.enumType = enumType;
        this.map = (Map<Enum, V>)map;
    }

    private Enum valueOf(Object key) {
        if (!(key instanceof String)) {
            throw new IllegalArgumentException("Only string keys are permitted");
        }

        return Enum.valueOf(enumType, (String)key);
    }

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean containsKey(Object key) {
        return map.containsKey(valueOf(key));
    }

    @Override
    public boolean containsValue(Object value) {
        return map.containsValue(value);
    }

    @Override
    public V get(Object key) {
        return map.get(valueOf(key));
    }

    @Override
    public V put(K key, V value) {
        return map.put(valueOf(key), value);
    }

    @Override
    public V remove(Object key) {
        return map.remove(valueOf(key));
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void clear() {
        map.clear();
    }

    @Override
    public Set<K> keySet() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Collection<V> values() {
        return map.values();
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        throw new UnsupportedOperationException();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文