java(jsp)的自定义标签
参考地址:http://dongguoh.iteye.com/blog/100782
TagSupport与BodyTagSupport的区别主要是标签处理类是否需要与标签体交互
用TagSupport实现的标签,都可以用BodyTagSupport来实现,因为BodyTagSupport继承了TagSupport。
doStartTag()方法是遇到标签开始时会呼叫的方法,其合法的返回值是EVAL_BODY_INCLUDE与SKIP_BODY,前者表示将显示标签间的文字,后者表示不显示标签间的文字;doEndTag()方法是在遇到标签结束时呼叫的方法,其合法的返回值是EVAL_PAGE 与 SKIP_PAGE,前者表示处理完标签后继续执行以下的JSP网页,后者是表示不处理接下来的JSP网页
首先是核心类,继承自BodyTagSupport类,:
ppackage cn.tag;
import java.io.IOException;
import java.util.Map;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class TestTag extends BodyTagSupport {
private static final long serialVersionUID = -5663050580910865400L;
/**
* 可以在这里进行一些初始化的工作
*/
public int doStartTag() throws JspException {
System.out.println("----doStartTag()----");
JspWriter out = this.pageContext.getOut();
try {
out.println("before");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this.EVAL_BODY_INCLUDE;
}
/**
* 核心处理标签的地方,业务逻辑在此实现,如:分页,根据参数返回给前台的值等等
*/
public int doEndTag() throws JspException {
JspWriter out = this.pageContext.getOut();
System.out.println("----doEndTag()----");
/**
* 获取参数
*/
Map map=this.pageContext.getRequest().getParameterMap();
if(map==null){
System.out.println("map is null");
}else{
System.out.println("map not null");
System.out.println(map.size());
}
try {
out.println("end");
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return super.doEndTag();
}
}
定义testTag.tld,貌似有些项是必需的,如下所示:
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>测试</description>
<tlib-version>1.1</tlib-version>
<short-name>tt</short-name>
<uri>/testTag</uri>
<tag>
<name>test</name>
<tag-class>cn.tag.TestTag</tag-class>
<body-content>JSP</body-content>
</tag>
</taglib>
测试页面,关键是要引入testTag.tld文件:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/WEB-INF/testTag.tld" prefix="tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'test.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<tags:test >测试</tags:test>
</body>
</html>
显示结果:
控制台:
----doStartTag()----
----doEndTag()----
map not null
页面:
before 测试end