java 如何在jsp中访问ModelMap?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3384080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:34:48  来源:igfitidea点击:

How do I access ModelMap in a jsp?

javajspspring-mvcjstl

提问by James

How can an object be accessed from the ModelMap in jsp so that a method can be called on it? Currently I recieve this error:

如何从 jsp 中的 ModelMap 访问一个对象,以便可以对其调用方法?目前我收到此错误:

Syntax error on token "$", delete this token

JSP

JSP

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

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"; 
    }
}

回答by skaffman

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 ModelMapwith the key 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.

在这里什么都不做,因为您没有ModelMap使用 key进入data。这仅在您想在整个会话中保留模型数据时才有用,在这里您似乎不需要这样做。

回答by Nikita Rybak

${varName}notation can be used in jstl only, and never - in plain java code. $character has no special meaning in Java.

${varName}符号只能在 jstl 中使用,永远不能在纯 java 代码中使用。$字符在 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")(不记得它是如何完成的)。