日期:2014-05-16  浏览次数:20363 次

jsp自定义标签常用方法属性
1。支持el表达式:
import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;
private Object value = null;
this.value = ExpressionEvaluatorManager.evaluate("value", value.toString(), Object.class, this, pageContext); 

2.用BeanUtil取属性值
import org.apache.commons.beanutils.PropertyUtils;
private String property=null;
Object propertyValue = PropertyUtils.getProperty(value, property);

3.设置request里的值
pageContext.setAttribute("var",propertyValue);

4。打印
pageContext.getOut().print(outputString);

5。取得父标签,取得想要的标签,即使它非父
getParent()
findAncestorWithClass(this,ancestorTag.class);

6。标签自带方法和常量,方法按照容器的调用顺序排列。示例  
 <c:if test="...">
  <c:out value="..."/>
 </c:if>
doStartTag : 容器解析到c:if左尖括号(“<”)时调用
doInitBody : 容器解析到c:if右尖括号(“>”)和c:out左尖括号(“<”)时调用
doAfterBody : 容器解析到c:out结束标记(“/>”)时调用
doEndTag :容器解析到c:if结束标记(“/>”)时调用

EVAL_BODY_SKIP : 通常在 doStartTag 方法里调用,忽略标签包括的内容,假如返回这个值,上面的c:if忽略c:out
EVAL_BODY_INCLUDE :通常在 doAfterBody 方法里调用,再次执行body,假如返回这个值,上面的c:out被执行多次
EVAL_PAGE :可在任何方法里调用。返回jsp页面






body-content:
根据web-jsptaglibrary_2_0.xsd(位于servlet-api.jar包($TOMCAT_HOME\common\lib)中的\javax\servlet\resources下,其中web.xml验证时所需要的xsd文件都位于此resources目录下),body-content的值有下面4种:
<xsd:enumeration value="tagdependent"/>
    <xsd:enumeration value="JSP"/>
    <xsd:enumeration value="empty"/>
    <xsd:enumeration value="scriptless"/>

tagdependent:标签体内容直接被写入BodyContent,由自定义标签类来进行处理,而不被JSP容器解释,
如下:
<test:myList>
select name,age from users
</test:myList>

JSP:接受所有JSP语法,如定制的或内部的tag、scripts、静态HTML、脚本元素、JSP指令和动作。如:
<my:test>
    <%=request.getProtocol()%>     // ②
</my:test>
具体可参考后面附源码。

empty:空标记,即起始标记和结束标记之间没有内容。
下面几种写法都是有效的,
<test:mytag />
<test:mytag uname="Tom" />
<test:mytag></test:mytag>

scriptless:接受文本、EL和JSP动作。如上述②使用<body-content> scriptless </body-content>则报错,具体可参考后面附源码。

rtexprvalue:
由请求时表达式来指定属性的值,默认为false,如下必须设置为true:
<test:welcome uname="<%=request.getParameter("username") %>" />


body-content为JSP/scriptless时标签体可以接受的代码(jasper-compiler.jar包($TOMCAT_HOME\common\lib)中的\org\apache\jasper\compiler\Parser.java中)