I'm currently running a working Spring + Apache Tiles webapp. I need to show some example code to explain my intention.
Apache Tiles Configuration:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
"http://tiles.apache.org/dtds/tiles-config_2_1.dtd">
<tiles-definitions>
<definition name="baseLayout" template="/WEB-INF/layouts/www_base.jsp" />
<definition name="home" extends="baseLayout">
<put-attribute name="body" value="/WEB-INF/views/home.jsp" />
</definition>
</tiles-definitions>
Example Controller:
@Controller
public class ExampleController {
@RequestMapping("/index.html")
public String index(Map<String, Object> map) {
map.put("hello", "world");
return "home";
}
}
This would display www_base.jsp
with home.jsp
as body
. I can use variable ${hello}
in www_base.jsp
as well as in home.jsp
.
But I don't want to set hello
in each Controller method to be able to use it in www_base.jsp
on each page.
Is there a way to set global variables for www_base.jsp
, e.g. in the constructor of ExampleController
?
UPDATE Example Code using a Map
@Controller
@RequestMapping("/")
public class BlogController {
@ModelAttribute
public void addGlobalAttr( Map<String, Object> map ) {
map.put("fooone", "foo1");
}
@RequestMapping("/index.html")
public String posts(Map<String, Object> map) {
map.put("foothree", "foo3");
return "posts";
}
}
Use a method annotated with @ModelAttribute:
An @ModelAttribute on a method indicates the purpose of that method is to add one or more model attributes. Such methods support the same argument types as @RequestMapping methods but cannot be mapped directly to requests. Instead @ModelAttribute methods in a controller are invoked before @RequestMapping methods, within the same controller.
@ModelAttribute methods are used to populate the model with commonly needed attributes for example to fill a drop-down with states or with pet types, or to retrieve a command object like Account in order to use it to represent the data on an HTML form.