简体   繁体   English

如何在JSP中使用null键获取Map值

[英]How to get Map value with the null key inside JSP

I have a Map<Integer, Object> in passed to JSP from a controller. 我从控制器传递给JSP的Map<Integer, Object> There is a null key with a default value, that means map.get(null) returns a default object. 有一个带有默认值的null键,这意味着map.get(null)返回一个默认对象。 keyObject.keyProp is Integer and might be null. keyObject.keyProp是Integer,可能为null。

When I use this in jsp 当我在jsp中使用它时

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

I do not get any output for the null keys. 我没有获得null键的任何输出。 Is there any way to make null keys work in jsp? 有没有办法让null键在jsp中工作?

It seems that the only way of getting the value for the null key using standard EL implementation is to call get() method on the map (considering that you said keyObject.keyProp resolves to Integer object): 似乎使用标准EL实现get() null键值的唯一方法是在地图上调用get()方法 (考虑到你说keyObject.keyProp解析为Integer对象):

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

I tested this solution and it works. 我测试了这个解决方案并且有效。

Actually, in this case, you can easily do without <c:out /> , just use plain EL where you need it, eg 实际上,在这种情况下,您可以轻松地在没有<c:out /> ,只需在您需要的地方使用普通EL,例如

${map.get(keyObject.keyProp)}

Simple example: 简单的例子:

TestMapServlet.java 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 测试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 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>


IMPORTANT NOTE 重要的提示
To be able to invoke methods with arguments using EL you must use minimum Servlet version 3.0 . 为了能够使用EL调用带有参数的方法,您必须使用最小的Servlet版本3.0
Quote from here: https://stackoverflow.com/tags/el/info 从这里引用: 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. 由于EL 2.2是作为Servlet 3.0 / JSP 2.2(Tomcat 7,Glassfish 3,JBoss AS 6等)的一部分维护的,因此可以在必要时使用参数调用非getter方法。


Apart from the above solution you could use custom Unified Expression Language implementation such as JUEL that has an alternative solution. 除了上述解决方案,您还可以使用自定义统一表达式语言实现,例如具有替代解决方案的JUEL

An explanation why it is not possible (in the standard implementation) to access map value by the null key using [] and the custom solution can be found in Java Unified Expression Language (JUEL) documentation (emphasis in paragraphs is mine): 解释为什么不可能(在标准实现中)使用[]和自定义解决方案通过null 访问映射值可以在Java统一表达式语言(JUEL)文档中找到 (段落中的重点是我的):

2.5. 2.5。 Advanced Topics 高级主题

... ...

Enabling/Disabling null Properties 启用/禁用空属性

The EL specification describes the evaluation semantics of base[property] . EL规范描述了base[property]的评估语义。 If property is null, the specification states not to resolve null on base. 如果property为null,则规范声明不在基础上解析null。 Rather, null should be returned if getValue(...) has been called and a PropertyNotFoundException should be thrown else. 相反,如果调用了getValue(...)并且应该抛出PropertyNotFoundException ,则应该返回null。 As a consequence, it is impossible to resolve null as a key in a map. 因此,无法将null解析为地图中的键。 However, JUEL's expression factory may be configured to resolve null like any other property value . 但是, JUEL的表达式工厂可以配置为像任何其他属性值一样解析null To enable (disable) null as an EL property value, you may set property javax.el.nullProperties to true (false). 要启用(禁用)null作为EL属性值,可以将属性javax.el.nullProperties设置为true(false)。

Assume that identifier map resolves to a java.util.Map . 假设标识符映射解析为java.util.Map

  • If feature javax.el.nullProperties has been disabled, evaluating ${base[null]} as an rvalue (lvalue) will return null (throw an exception). 如果已禁用feature javax.el.nullProperties ${base[null]}作为rvalue(lvalue)进行求值将返回null(抛出异常)。

  • 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. 如果已启用功能javax.el.nullProperties ${base[null]}作为rvalue(左值)进行求值将获取(放置)该映射中的键null值。 The default is not to allow null as an EL property value. 默认情况下不允许null作为EL属性值。

... ...

Hope this will help. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM