动态模板是模块化WEB 页布局设计的强大手段。Struts 模板标记库定义了自定义标记来实现动态模板。
插入标记
<template:insert>标记能够在应用程序的JSP 页中插入动态模板。这个标记只有一个template 属性,用来定义模板JSP 页。要插入到模板的页是有多个<template:put>标记来指定的,而这些标记被定义为<template:insert>标记的主体内容。
放置标记
<template:put>标记是<template:insert>标记内部使用的,用来指定插入到模板的资源。属性如下:
属性描述
content 定义要插入的内容,比如一个JSP 文件或一个HTML 文件
direct 如果这个设置为true,由content 属性指定的内容将直接显示在JSP 上而不是作为包含文件
Name 要插入的内容的名称
Role 如果设置了这个属性,只有在当前合法用户具有特定角色时才能进行内容的插入。
获得标记
在模板JSP 页中使用<template:get>标记能够检索由<template:put>标记插入到JSP页的资源。属性如下:
属性描述
Name 由<template:put>标记插入的内容的名称
Role 如果设置了这个属性,只有在当前合法用户具有特定角色时才能进行内容的检索
使用模板标记
首先编写一个模板JSP 页,它将被所有的web 页使用:
<html> <%@ taglib uri=”/template” prefix=”template” %> <head> <title></title> </head> <body> <table width=”100%” height=”100%” > <tr height=”10%”> <td> <template:get name=”header”/> </td> </tr> <tr height=”80%”> <td> <template:get name=”content”/> </td> </tr> <tr height=”10%”> <td> <template:get name=”footer”/> </td> </tr> </table> </body> </html>
我们将这个文件命名为template.jsp。这个文件使用<template:get>标记来获得由JSP页使用<template:put>标记提供的内容,并且将内容在一个HTML 表格中显示出来。这三个内容是标题,内容和页脚。典型的内容JSP 会是这样:
<%@ taglib uri=”/template” prefix=”/template” %> <template:insert template=”template.jsp”> <template:put name=”header” content=”header.html”/> <template:put name=”content” content=”employeeList.jsp”/> <template:put name=”footer” content=”footer.html”/> </template:insert>
这个应用程序JSP 页使用<template:insert 标记来定义模板,然后使用<template:put>标记将特定内容名称指定的资源放到模板JSP 页中。如果我们有上百个布局相同的页,但突然想改变这个模板,我们只需要改变template.jsp 文件。