JSP自定義標籤

自定義標籤

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.0</tlib-version>

<short-name>mytag</short-name>

<uri>/helloworldtaglib</uri>

<tag>

<name>helloworld</name>

<tag-class>mytag.HelloTag</tag-class>

<body-content>empty</body-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 here</title>

</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.0</tlib-version>

<short-name>product</short-name>

<uri>/producttaglib</uri>

<tag>

<name>list</name>

<tag-class>mytag.ProductTag</tag-class>

<body-content>empty</body-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 here</title>

</head>

<body>

<mytag:helloworld/>

<product:list/>

</body>

</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章