【问题标题】:Pass global variables to Spring + Apache Tiles将全局变量传递给 Spring + Apache Tiles
【发布时间】:2012-06-24 14:07:03
【问题描述】:

我目前正在运行一个有效的 Spring + Apache Tiles webapp。 我需要展示一些示例代码来解释我的意图。

Apache Tiles 配置:

<?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>

示例控制器:

@Controller
public class ExampleController {
    @RequestMapping("/index.html")
    public String index(Map<String, Object> map) {
        map.put("hello", "world");
        return "home";
    }
}

这会将www_base.jsp 和home.jsp 显示为body。我可以在www_base.jsp 和home.jsp 中使用变量${hello}。

但我不想在每个 Controller 方法中设置 hello 以便能够在每个页面上的 www_base.jsp 中使用它。

有没有办法为www_base.jsp 设置全局变量,例如在ExampleController的构造函数中?

更新 使用地图的示例代码

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

【问题讨论】:

    标签: spring spring-mvc tiles tiles2 apache-tiles


    【解决方案1】:

    使用method annotated with @ModelAttribute:

    方法上的@ModelAttribute 表示该方法的目的是 添加一个或多个模型属性。这些方法支持相同的 参数类型为 @RequestMapping 方法,但不能被映射 直接请求。而是控制器中的 @ModelAttribute 方法 在@RequestMapping 方法之前调用,在同一个 控制器。

    @ModelAttribute 方法通常用于填充模型 所需的属性,例如用状态或用填充下拉列表 宠物类型,或检索像 Account 这样的命令对象,以便 用它来表示 HTML 表单上的数据。

    【讨论】:

      猜你喜欢
      • 2014-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      • 2018-09-02
      • 1970-01-01
      相关资源
      最近更新 更多