自定义标签

1.编写标签处理类,继承SimpleTagSupport

package mytag;

import java.io.IOException;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.SimpleTagSupport;

publicclass HelloTag extendsSimpleTagSupport{

@Override

publicvoiddoTag() throws JspException, IOException {

this.getJspContext().getOut().write("Hello World");

}

}

2.标签处理类必须在包里,不能是裸体类

3.WEB-INF目录或子目录下建立一个helloworld.tld

xmlversion="1.0"encoding="UTF-8"?>

<taglibxmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"version="2.0"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">

<tlib-version>1.0tlib-version>

<short-name>mytagshort-name>

<uri>/helloworldtagliburi>

<tag>

<name>helloworldname>

<tag-class>mytag.HelloTagtag-class>

<body-content>emptybody-content>

tag>

taglib>

4.建立testTag.jsp

<%@pagelanguage="java"contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<%@taglibprefix="mytag"uri="/helloworldtaglib"%>

DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">

<title>Insert title heretitle>

head>

<body>

<mytag:helloworld/>

body>

html>

实例二

1.WEB-INF/product.tld

xmlversion="1.0"encoding="UTF-8"?>

<taglibxmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"version="2.0"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">

<tlib-version>1.0tlib-version>

<short-name>productshort-name>

<uri>/producttagliburi>

<tag>

<name>listname>

<tag-class>mytag.ProductTagtag-class>

<body-content>emptybody-content>

tag>

taglib>

2.

package mytag;

import java.io.IOException;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.SimpleTagSupport;

publicclass ProductTag extends SimpleTagSupport{

@Override

publicvoid doTag() throws JspException, IOException {

this.getJspContext().getOut().write("**********");

}

}

3.

<%@pagelanguage="java"contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<%@taglibprefix="mytag"uri="/helloworldtaglib"%>

<%@taglibprefix="product"uri="/producttaglib"%>

DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">

<title>Insert title heretitle>

head>

<body>

<mytag:helloworld/>

<product:list/>

body>

html>