views:

91

answers:

2

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:

Syntax error on token "$", delete this token

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"; 
    }
}
+1  A: 

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

Try something like pageContext.getAttribute("varName") or session.getAttribute("varName") (don't remember how exactly it's done).

Nikita Rybak
Your first statement is misleading. You mean to say JSP here, not JSTL.
BalusC
+3  A: 

The <% %> syntax is deprecated, and shouldn't be used any more.

The equivalent in modern JSP of your JSP fragment would be:

<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. This is only useful if you want to keep the model data across the session, which it doesn't seem you need to here.

skaffman
Wow ok, thanks very much, that's so much easier. The reason for the 'data' session attribute was that I thought 'menus' would be accessible by 'data.menus' because it didn't seem possible to create either multiple entries in @SessionAttributes, e.g. '@SessionAttributes("menus","anotherSessionVar")' or alternatively have multiple '@SessionAttributes' annotations. Any idea how this can be done?
James
@James: Try `@SessionAttributes({"menus","anotherSessionVar"})`
skaffman