ITEEDU

JSP/Servlet: <jsp: doBody>、<jsp:invoke>与指令元素

在Tag File中可以使用<jsp:doBody>与<jsp:invoke>动作元素,前者是用来处理卷标本体文字,后者则是用来设 定标签间的Fragment,这两个动作元素搭配着attribute与variable两个指令元素来作示范会比较好说明。

首先介绍<jsp:doBody>您可以用它来决定是否显示本体文字,例如撰写如下的Tag File:

check.tag

<%@attribute name="password"%>
<% if(password.equals("1234")) { %> 
<jsp:doBody/> 
<% } else { %> 
密码不正确 
<% } %> 

必须先说明的是,这边使用了Scriptlet,这并不是一个良好的示范,若能搭配JSTL或自订标签库来完成Tag File的撰写会是比较好的,这边纯綷是为了说明方便才使用了Scriptlet。
上面这个Tag File会检查传入的属性password是否符合我们设定的密码,如果符合就执行<jsp:doBody>,表示显示卷标之间的本体文字, 否则显示密码不正确的讯息,attribute指令元素可以指定自订卷标所使用的属性文字,可以使用下面的JSP网页来测试:

test.jsp
<%@taglib prefix="caterpillar" tagdir="/WEB-INF/tags/" %> 
<html> 
<body> 
<caterpillar:check password="${ param.pwd }"> 
您的秘密礼物在此! 
</caterpillar:check> 
</body> 
</html> 

您可以发现,Tag File即使是用来当作自订标签库的简便方式,也是十分的方便,不需要在tld档中作额外的设定,也可以得到相关的功能。
attribute除了指定属性文字之外,也可以将属性当作Fragment传入,方便在Tag File中作个别的处理,例如下面撰写一个table.tag:

table.tag
<%@attribute name="frag1" fragment="true"%> 
<%@attribute name="frag2" fragment="true"%>
<table border="1"> 
<tr> 
<td><b>frag1</b></td> 
<td><jsp:invoke fragment="frag1"/></td> 
</tr> 
<tr> 
<td><b>frag2</b></td> 
<td><jsp:invoke fragment="frag2"/></td> 
</tr> 
</table> 

在这个Tag File中,将attribute的属性设定为Fragment,然后想取得指定的Fragment的话,就可以使用<jsp: invoke>动作元素,并指定Fragment的名称,使用下面这个JSP网页来测试:

test.jsp
<%@taglib prefix="caterpillar" tagdir="/WEB-INF/tags/" %> 
<html> 
<body> 
<caterpillar:table> 
<jsp:attribute name="frag1"> 
Fragment 1 here 
</jsp:attribute> 
<jsp:attribute name="frag2"> 
Fragment 2 here 
</jsp:attribute> 
</caterpillar:table> 
</body> 
</html> 

在JSP网页中,同样的是使用<jsp:attribute>来说定Fragment的文字内容,执行这个JSP网页,会传回以下的内容:

<html> 
<body>
<table border="1"> 
<tr> 
<td><b>frag1</b></td> 
<td>Fragment 1 here</td> 
</tr> 
<tr> 
<td><b>frag2</b></td> 
<td>Fragment 2 here</td> 
</tr> 
</table> 
</body> 
</html> 

在Tag File与JSP网页之间,可以使用variable指令元素设定Scripting Variable,以在两者之间传递变量内容,例如撰写以下的Tag File:

precode.tag
<%@attribute name="preserve" fragment="true" %> 
<%@variable name-given="code" scope="NESTED" %>
<jsp:doBody var="code" />
<table border="1"> 
<tr> 
<td> 
<pre><jsp:invoke fragment="preserve"/></pre> 
</td> 
</tr> 
</table> 

在这个Tag File中,使用variable设定Scripting Variable为"code",作用范围为"NESTED",也就是在起始卷标与结束卷标之间,而其中<jsp:doBody>中多了一项 属性var,表示在JSP网页中的<jsp:body>卷标中的文字内容将设定给"code"变量,可以用下面这个JSP网页来测试:

test.jsp
<%@ taglib prefix="caterpillar" tagdir="/WEB-INF/tags" %> 
<html> 
<body> 
<caterpillar:precode> 
<jsp:attribute name="preserve"> 
<b>${ code }</b> 
</jsp:attribute>
<jsp:body> 
PROGRAM MAIN 
PRINT 'HELLO' 
END 
</jsp:body> 
</caterpillar:precode> 
</body> 
</html> 

<jsp:body>之间的虚拟程序代码将会传入给"code"变量,由于它是Scripting Variable,可以在标签之内起作用,所以在<jsp:attribute>中的EL式${code}可以取得Tag File中"code"的内容,也就是<jsp:body>传入的文字,之后我们将<jsp:attribute>的内容当作 Fragment在Tag File中作处理,结果将会如以下的网页:

<html> 
<body> 
<table border="1"> 
<tr> 
<td> 
<pre><b> 
PROGRAM MAIN 
PRINT 'HELLO' 
END 
</b></pre> 
</td> 
</tr> 
</table> 
</body> 
</html>