how to access a ModelAndView object within the jsp

2020-05-22 09:53发布

I have a code like this in my controller.

ModelAndView result = new ModelAndView("person/sometrends");  
result.addObject("data", data);  // data -> Map

In my JSP page I have written some Java code that is dependent on the data object. How can I get that data object within the JSP code?

I tried something like this (pseudo code).

<%
    Map x = ${data};
%>

But that doesn't work. Not sure how to access it.

标签: spring-mvc
6条回答
爷、活的狠高调
2楼-- · 2020-05-22 10:00

Let me more specific, if you want to use jsp instead of jstl to access the Model you would do something like this:

<% Map x = (Map)request.getAttribute("data") %>
查看更多
淡お忘
3楼-- · 2020-05-22 10:09

try<% String username = (String)request.getAttribute("data"); %>

查看更多
▲ chillily
4楼-- · 2020-05-22 10:10

In a scriptlet, you use the request object like so:

<% Map myMap = (Map) request.getAttribute("data"); %>

If you want to use something like JSTL instead of a scriptlet, you could do:

<c:forEach var="entry" items="${data}">
Name:  ${entry.key} <br/>
Value: ${entry.value} <br/>
</c:forEach>

As Davemeister and novice pointed out, combining EL inside a scriptlet was the root cause of your error.

查看更多
趁早两清
5楼-- · 2020-05-22 10:17

Try this:

request.getAttribute("data")
查看更多
戒情不戒烟
6楼-- · 2020-05-22 10:21

Using expression language inside the scriptlet would be the cause.

查看更多
爷的心禁止访问
7楼-- · 2020-05-22 10:21

include: <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

and then...

<%
    Map x = ${data};
%>
查看更多
登录 后发表回答