简体   繁体   English

如何在jsp中访问ModelMap?

[英]How do I access ModelMap in a jsp?

How can an object be accessed from the ModelMap in jsp so that a method can be called on it? 如何在jsp中从ModelMap访问对象,以便可以在其上调用方法? Currently I recieve this error: 目前我收到此错误:

Syntax error on token "$", delete this token

JSP JSP

<body>
        <% MenuWriter m = ${data.menus} %>
        <%= m.getMenus()%>  
</body>

Java Java的

@Controller
@RequestMapping("/dashboard.htm")
@SessionAttributes("data")
public class DashBoardController {

    @RequestMapping(method = RequestMethod.GET)
    public String getPage(ModelMap model) {
        String[] menus = { "user", "auth", "menu items", };
        String[] files = { "menu", "item", "files", };
        MenuWriter m = new MenuWriter(menus, files);
        model.addAttribute("menus", m);

        String[] atocs = { "array", "of", "String" };
        model.addAttribute("user_atocs", atocs);

        return "dashboard"; 
    }
}

The <% %> syntax is deprecated, and shouldn't be used any more. 不推荐使用<% %>语法,不应再使用它。

The equivalent in modern JSP of your JSP fragment would be: JSP片段的现代JSP中的等价物将是:

<body>
   ${menus.menus}
</body>

Obviously, that looks confusing, so you may want to consider renaming parts of your model for clarity. 显然,这看起来令人困惑,因此您可能需要考虑重新命名模型的某些部分以保持清晰。

Also, your annotation 另外,你的注释

@SessionAttributes("data")

does nothing here, since you have no entry in the ModelMap with the key data . 这里什么都不做,因为你在ModelMap没有关键data条目。 This is only useful if you want to keep the model data across the session, which it doesn't seem you need to here. 这仅在您希望在会话中保留模型数据时才有用,这在您看来不需要。

${varName} notation can be used in jstl only, and never - in plain java code. ${varName}表示法只能在jstl中使用,而且永远不会在普通的java代码中使用。 $ character has no special meaning in Java. $ character在Java中没有特殊含义。

Try something like pageContext.getAttribute("varName") or session.getAttribute("varName") (don't remember how exactly it's done). 尝试使用pageContext.getAttribute("varName")session.getAttribute("varName") (不记得它是如何完成的)。

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

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