本文学习的目的,知道自定义标签是如何实现的。做一个最简单的自定义标签<mytag:hello/>,效果是打印hello world!
1、编写标签处理类HelloTag(实现javax.servlet.jsp.tagext.Tag类)
package cn.itcast.tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
public class HelloTag implements Tag {
private PageContext pageContext;
private Tag tag;
public int doEndTag() throws JspException {
try {
pageContext.getOut().print(/"hello world!/");
} catch (IOException e) {
e.printStackTrace();
}
return Tag.EVAL_PAGE;
}
public int doStartTag() throws JspException {
return Tag.SKIP_BODY;
}
public Tag getParent() {
return null;
}
public void release() {
}
public void setPageContext(PageContext arg0) {
this.pageContext = arg0;
}
public void setParent(Tag arg0) {
this.tag = arg0;
}
}
注意Tag中定义的几个常量的含义(EVAL_PAGE,SKIP_BODY等)
2、编写hellotag.tld标签定义文件
<?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.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>tagSample</short-name>[Page]
<uri>/hellotag</uri>
<tag>
<name>hello</name>
<tag-class>cn.itcast.tag.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
3、编写测试jsp文件
<%@ page contentType=/"text/html; charset=GBK/" %>
<%@ page errorPage=/"error.jsp/" %>
<%@ taglib uri=/"/WEB-INF/hellotag.tld/" prefix=/"mytag/" %>
<html>
<head>
<title></title>
</head>
<body>
<mytag:hello/>
<mytag:hello>haha</mytag:hello>
</body>
</head>
测试结果应该是打印出两个hello world!
标签库的优点
1、最大限度地消除jsp页面中嵌入的java代码
2、增强代码扩展性、可读性、代码复用,简化了jsp页面编写的工作量
新闻热点
疑难解答