1、自定义Tag Library类:SexIdTag
(1)需要import三个类:JspException、JspWriter、TagSupport。
(2)继承TagSupport,使用其提供的doStartTag、doEndTag、doAfterBody方法。
(3)声明属性(即后期使用标签时要处理的数据),要利用JavaBean的getter和setter机制,需要属性的get、set方法。
(4)标签被执行时,首先呼叫doStartTag方法,主要是对数据的处理,返回值有2种:
<1>EVAL_BODY_INCLUDE:表示显示标签间的本体文字。
<2>SKIP_BODY:表示不显示标签间的本体文字。
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import com.mvc.constant.RALConstants;
public class SexIdTag extends TagSupport{
private String sexId;
public String getSexId() {
return sexId;
}
public void setSexId(String sexId) {
this.sexId = sexId;
}
public int doStartTag() throws JspException{
JspWriter out = this.pageContext.getOut();
if(RALConstants.getSexId()!=null){
try {out.print(RALConstants.getSexId().get(this.sexId));
} catch (IOException e) {e.printStackTrace();}
return this.EVAL_BODY_INCLUDE;
}else{ return this.SKIP_BODY; }}}
【解释】
RALConstants.getSexId()取得的是性别的键值对Map:<"F","女">、<"M","男">
doStartTag是将传递的key值sexId,转为value值显示在页面标签处。
2、定义.tld文档
(1)每个Tag Library需要定义一组<tag></tag>
1》 <name>:设定在JSP页面中使用的标签名
2》 <body-content>:设置为empty表示标签不处理本体文字
3》 <attribute>:设定传入的参数;
# 里面的<name>:值要对应SexIdTag类里面的属性名。
# 里面的<required>:设置为true表示必须传入变量。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.1.1</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>SampleTool</short-name>
<uri>/sampletool</uri>
<display-name>SampleTool Custom tag library</display-name>
<description>Custom tag library</description>
<tag>
<name>sexIdTag</name>
<tag-class>com.iholtek.mvc.tag.SexIdTag</tag-class>
<body-content>empty</body-content>
<description></description>
<attribute>
<name>sexId</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
3、在页面中使用
url就是tld所在位置,prefix是jsp网页要使用这个tablib的名称
<%@ taglib prefix = "sampletool" uri = "/WEB-INF/tlds/sampletoolsys.tld" %>使用:
【解释】
假定一个页面上有Sex的下拉框select,每个option的value是SexId,选择完提交后跳转到另一个页面,取得的是key值,通过自定义标签转成value值显示。
<sampletool:sexIdTag sexId="${guests.sex}" />
sampletool:sexIdTag 即呼叫sexIdTag.java,并传入一个变量sexId,此时sexIdTag.java调用doStartTag,由key得到value,回传处理结果到jsp页面的该位置。
没错则返回EVAL_BODY_INCLUDE显示标签本体文字。