将映射传递给JSP

时间:2013-12-15 15:01:45

标签: java spring jsp spring-mvc

我是Spring MVC / JSP世界的新手。对不起,如果下面的问题很明显,

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

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);

但是,当我尝试使用以下scriplet 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

如果我尝试使用Expression获取值,则会出现相同的异常: -

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

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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]}"/>