廢話不多說,通過SimpleTag(JSP2.0以上)接口,可以定製自己的標籤。
-參考資料:《Servlet和JSP學習指南》
要自定義標籤,要做以下兩件事:
- 編寫標籤處理器(寫java類)
- 註冊標籤
1.編寫標籤處理器
package myTag;
import java.io.IOException;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.JspTag;
import javax.servlet.jsp.tagext.SimpleTag;
public class MyFirstTag implements SimpleTag {
private JspContext jspContext;
//setJspContext , 這個方法把JSP容器接受到的JspContext賦給自定義標籤
public void setJspContext(JspContext jspContext) {
System.out.println("setJspContext");
this.jspContext = jspContext;
}
//setJspBody
public void setJspBody(JspFragment body) {
System.out.println("setJspBody");
}
public void doTag() throws IOException, JspException {
System.out.println("doTag");
/* 通過jsp容器賦予的JspContext的到JspWriter */
JspWriter writer = jspContext.getOut();
writer.print("this is my first tag.");
}
//Parent sett,gett方法
public void setParent(JspTag parent) {
System.out.println("setParent");
}
public JspTag getParent() {
System.out.println("getParent");
return null;
}
}
2.註冊標籤
<?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
web-jsptaglibrary_2_1.xsd"
version="2.1">
<description>
Simple tag examples
</description>
<tlib-version>1.0</tlib-version>
<short-name>My First Taglib Example</short-name>
<!-- 定義一個tag,一個tld文件中可以包含多個tag標籤 -->
<tag>
<name>firstTag</name><!-- 名稱 -->
<tag-class>myTag.MyFirstTag</tag-class><!-- 類全名 -->
<body-content>empty</body-content>
</tag>
</taglib>
好了,可是使用了:
<%@ taglib uri="/WEB-INF/mytags.tld" prefix="easy" %>
<html>
<head></head>
<body>
<easy:firstTag></easy:firstTag>
</body>
</html>
注意:這些文件存放位置應該如下:
頁面效果及後臺輸出: