【问题标题】:Passing Map to JSP将映射传递给 JSP
【发布时间】:2013-12-15 15:01:44
【问题描述】:

我是 Spring MVC / JSP 世界的新手。抱歉,如果以下问题很明显,

我有一张地图Map<BigInteger, String> reports = new HashMap<>();,需要从控制器传递给JSP。 map的内容会是这样的

reports.put(new BigInteger("101"), "type1");
reports.put(new BigInteger("102"), "type2");
reports.put(new BigInteger("103"), "type3");

从 Spring MVC 控制器中,我将这张地图传递如下:

ModelAndView mav = new ModelAndView("view");
mav.addObject("reports", reports);

但是当我尝试使用以下脚本在 view.jsp 中访问它时:-

<% String a1 = request.getAttribute("reports").get(new BigInteger("101")); %>

但这给了我以下例外:

PWC6199: Generated servlet error:
cannot find symbol
  symbol:   method get(java.math.BigInteger)
  location: class java.lang.Object

如果我尝试使用以下表达式获取值,则会出现相同的异常:-

<%= request.getAttribute("reports").get(new BigInteger("101")) %>

任何帮助将不胜感激。

【问题讨论】:

    标签: java spring jsp spring-mvc


    【解决方案1】:

    request.getAttribute("reports") 返回Object 的引用而不是Map,您必须转换

    你最好使用 JSTL 来避免视图模板中的 java 代码

    【讨论】:

      【解决方案2】:

      正如 Jigar Joshi 所说,您需要进行投射才能访问 JSP 中的地图

      <%= ((Map<BigInteger, String>) request.getAttribute("reports")).get(new BigInteger("101")) %>
      

      然而,如前所述,使用 EL 表达式会更简洁。由于地图由BigInteger 键入,您需要将键转换为StringLong,因此它们是accessible to EL

      使用String 键:

      reports.put("101", "type1");
      

      在JSP中你可以使用:

      <c:out value="${reports['101']}"/>
      

      或使用Long 键:

      reports.put(101L, "type1");
      

      你可以使用:

      <c:out value="${reports[101]}"/>
      

      【讨论】:

        猜你喜欢
        • 2013-09-04
        • 1970-01-01
        • 2017-06-19
        • 2015-10-23
        • 1970-01-01
        • 1970-01-01
        • 2020-06-16
        • 2021-07-28
        • 2018-04-30
        相关资源
        最近更新 更多