jsp2.0的tag,jsp自定义标签,类似jsp动态include

自定义标签好像现在已经很少使用

我们自定义的tag类需要继承TagSupport类,相应的方法返回值意义如下。

EVAL_BODY_INCLUDE:把Body读入存在的输出流中,doStartTag()函数可用
EVAL_PAGE:继续处理页面,doEndTag()函数可用
SKIP_BODY:忽略对Body的处理,doStartTag()和doAfterBody()函数可用
SKIP_PAGE:忽略对余下页面的处理,doEndTag()函数可用
EVAL_BODY_TAG:已经废止,由EVAL_BODY_BUFFERED取代
EVAL_BODY_BUFFERED:申请缓冲区,由setBodyContent()函数得到的BodyContent对象来处理tag的body,如果类实现了BodyTag,那么doStartTag()可用,否则非法

jsp 2.0提供一种新的用法“jsp tag”

只需要写XXX.tag文件,jsp页面中就可以引入

<%@ taglib prefix="tags" tagdir="/WEB-INF/tags/XXX.tag" %>

XXX.tag文件如下,这个tag文件实现的功能是:当前用户拥有权限时,才输出tag内部的html

  
    
    
      
<% @ tag import = " netid.right.util.SysrightUtil " %>
<% @ tag import = " netid.right.util.SysrightConstants " %>
<% @ attribute name = " rightUrl " description = " rightUrl " %>
<%

String adminId
= SysrightUtil.getCookieInfo(request, SysrightConstants.RIGHT_USERID);
String rights
= (String) SysrightConstants.RIGHT_MAP.get(adminId);
if (rights != null && rights.contains(rightUrl)) {
%>
< jsp:doBody />
<%
}
%>


下面是抄自JSP 2.0 tag files 文档中的一段例子
原文http://www.softwaresummit.com/2005/speakers/BergmanJSP2.0TagFiles.pdf
example.tag:
    
      
<% @ tag dynamic - attributes = " attrMap " body - content = " scriptless " %>
<% @ attribute name = " bodyColor " required = " true " %>
<% @ attribute name = " listopen " fragment = " true " required = " true " %>
<% @ attribute name = " listitem " fragment = " true " required = " true " %>
<% @ attribute name = " listclose " fragment = " true " required = " true " %>
<% @ variable name - given = " aKey " scope = " NESTED%>
<% @ variable name - given = " aValue " scope = " NESTED%>
<% @ taglib prefix = " c " uri = " http://java.sun.com/jsp/jstl/core " %>
< jsp:invoke fragment = " listopen " />
< c:forEach var = " attr " items = " ${attrMap} " >
< c:set var = " aKey " value = " ${attr.key} " />
< c:set var = " aValue " value = " ${attr.value} " />
< jsp:invoke fragment = " listitem " />
</ c:forEach >
< jsp:invoke fragment = " listclose " />
< FONT color = " ${bodyColor} " >< jsp:doBody /></ FONT >
example.jsp:
     
       
<% @ taglib prefix = " c " uri = " http://java.sun.com/jsp/jstl/core " %>
<% @ taglib prefix = " my " tagdir = " /WEB-INF/tags/ " %>
< my:example bodyColor = " blue " first = " 1 " second = " 2 " third = " 3 " fourth = " 4 " fifth = " 5 " sixth = " 6 " >
< jsp:attribute name = " listopen " >
< table border = " 1 " >
< caption > Dynamic Attributes </ caption >
< tr >< TH > Name </ TH >< TH > Value </ TH ></ tr >
</ jsp:attribute >
< jsp:attribute name = " listclose " >
</ table >
</ jsp:attribute >
< jsp:attribute name = " listitem " >
< tr >
< td > ${aKey} </ td >
< td > ${aValue} </ td >
</ tr >
</ jsp:attribute >
< jsp:body > this is body text. </ jsp:body >
</ my:example >

你可能感兴趣的:(jsp自定义标签)