java - 如何在JSP中使用空键获取Map值

标签 java jsp map el

我有一个 Map<Integer, Object>从 Controller 传递给 JSP。有一个带有默认值的空键,这意味着 map.get(null)返回一个默认对象。 keyObject.keyProp是整数,可能为空。

当我在jsp中使用它的时候

<c:out value="${map[keyObject.keyProp]}"/>

我没有得到空键的任何输出。有什么方法可以使空键在 jsp 中工作吗?

最佳答案

这似乎是获取 null 值的唯一方法使用标准 EL 实现的关键是 调用 get() map 上的方法(考虑到您说 keyObject.keyProp 解析为 Integer 对象):

<c:out value="${map.get(keyObject.keyProp)}" />

我测试了这个解决方案并且它有效。

实际上,在这种情况下,您可以轻松地不用 <c:out /> ,只需在需要的地方使用普通 EL,例如

${map.get(keyObject.keyProp)}

简单示例:

TestMapServlet.java

package com.example;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

import java.util.Map;
import java.util.HashMap;

import java.io.IOException;

public class TestMapServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
        Map<Integer, Object> map = new HashMap<Integer, Object>();
        Integer noValueInt = null;
        Integer one = new Integer(1);
        Integer two = new Integer(2);

        map.put(noValueInt, "Default object for null Integer key");
        map.put(one, "Object for key = Integer(1)");
        map.put(two, "Object for key = Integer(2)");

        request.setAttribute("map", map);
        request.setAttribute("noValueInt", noValueInt);
        request.setAttribute("one", one);
        request.setAttribute("two", two);

        request.getRequestDispatcher("/test-map.jsp").forward(request, response);
    }
}


test-map.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <h1>Testing access to java.util.Map using just EL</h1>
    <p><b>\${map.get(noValueInt)}</b>: ${map.get(noValueInt)}</p>
    <p><b>\${map[one]}</b>: ${map[one]}</p>
    <p><b>\${map[two]}</b>: ${map[two]}</p>

    <h1>Testing access to java.util.Map using JSTL and EL</h1>
    <p><b>&lt;c:out value="\${map.get(noValueInt)}" /&gt; </b>: <c:out value="${map.get(noValueInt)}" /></p>
    <p><b>&lt;c:out value="\${map[one]}" /&gt; </b>: <c:out value="${map[one]}" /></p>
    <p><b>&lt;c:out value="\${map[two]}" /&gt; </b>: <c:out value="${map[two]}" /></p>

    <h2>Printing java.util.Map keys and values (when Key = null, the <i>null</i> won't be shown)</h2>
    <c:forEach items="${map}" var="entry">
        <p><b>Key</b> = "${entry.key}", <b>Value</b> = "${entry.value}"</p>
    </c:forEach>
</body>
</html>


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <servlet>
        <servlet-name>Test Map Servlet</servlet-name>
        <servlet-class>com.example.TestMapServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Test Map Servlet</servlet-name>
        <url-pattern>/TestMap.do</url-pattern>
    </servlet-mapping>

</web-app>


重要提示
为了能够使用 EL 调用带参数的方法,您必须使用最低 Servlet 版本 3.0
从这里引用:https://stackoverflow.com/tags/el/info

Since EL 2.2, which is maintained as part of Servlet 3.0 / JSP 2.2 (Tomcat 7, Glassfish 3, JBoss AS 6, etc), it's possible to invoke non-getter methods, if necessary with arguments.


除了上述解决方案之外,您还可以使用自定义统一表达式语言实现,例如JUEL有替代解决方案。

解释为什么不可能(在标准实现中)通过 null 访问 map key 使用 []自定义解决方案可在 Java Unified Expression Language (JUEL) documentation 中找到(段落中的重点是我的):

2.5. Advanced Topics

...

Enabling/Disabling null Properties

The EL specification describes the evaluation semantics of base[property]. If property is null, the specification states not to resolve null on base. Rather, null should be returned if getValue(...) has been called and a PropertyNotFoundException should be thrown else. As a consequence, it is impossible to resolve null as a key in a map. However, JUEL's expression factory may be configured to resolve null like any other property value. To enable (disable) null as an EL property value, you may set property javax.el.nullProperties to true (false).

Assume that identifier map resolves to a java.util.Map.

  • If feature javax.el.nullProperties has been disabled, evaluating ${base[null]} as an rvalue (lvalue) will return null (throw an exception).

  • If feature javax.el.nullProperties has been enabled, evaluating ${base[null]} as an rvalue (lvalue) will get (put) the value for key null in that map. The default is not to allow null as an EL property value.

...

希望这会有所帮助。

关于java - 如何在JSP中使用空键获取Map值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14388149/

相关文章:

映射为匿名结构成员

java - 定时等待认证模拟考试

java - 为什么 Files.isHidden() 不能正常工作?

java - 如何JSP用一种布局显示多个页面(示例index.jsp?page=about显示about.jsp)

html - JSP - 将数据从 Controller 传输到 Scriptlet

java - 无法在 spring boot security 中登录到我的自定义登录页面

java - 如何在 JUnit 4 中编写assertTimeoutPreemptively (JUnit 5)?

java - 如何将带有GSON的JSON反序列化为对应的泛型Java类型?

c++ - 是否可以将默认构造函数设置为 `std::map<T1, T2>` 值?

performance - 我如何有效地(内存/时间)修改 Tcl 中列表的所有元素?