學到了一個簡單的jsp自定義標簽,后面有更多的例子,會更新出來:
例子1:
步驟:
1.編寫標簽實現類:
繼承javax.servlet.jsp.tagext.SimpleTagSupport;
重寫doTag,實現在網頁上輸出;
2.在web-inf目錄或其子目錄下,建立helloword.tld文件,即自定義標簽的說明文件
注意:標簽處理類必須放在包中,不能是裸體類;不需要修改web.xml;
//tld: tag lib description 標簽庫描述
java代碼:
package com.mytag; import java.io.IOException; import javax.servlet.jsp.JspException; public class HelloTag extends javax.servlet.jsp.tagext.SimpleTagSupport{ @Override public void doTag() throws JspException, IOException { //拿到當前這個jsp文件的上下文,拿到輸出流 getJspContext().getOut().write("HelloWorld!"); } }
jsp代碼:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="/helloworldtaglib" prefix="mytag"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>測試自定義jsp tag標簽</title> </head> <body> <mytag:helloworld/> </body> </html>
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"> <tlib-version>1.0</tlib-version> <short-name>mytag</short-name> <uri>/helloworldtaglib</uri> <tag> <name>helloworld</name> <tag-class>com.mytag.HelloTag</tag-class> <body-content>empty</body-content> </tag> </taglib> <!-- 解釋: --> <!-- short-name: 這個標簽的前綴名 這里就是<mytag: /> 可以防止和別人定義的標簽重名的沖突--> <!-- uri: 當前這個tld文件要訪問它的時候使用的獨一無二的標示符,用來找相應的tld文件 --> <!-- body-content: 開始標簽和結束標簽之間的信息,標簽體; 如<img/>標簽體就是空的 --> <!-- tomcat看到<mytag:helloworld/>的helloworld時候,就在tab下面找name=helloworld對應的class,調用doTag方法 -->
因為我這里的tld文件是放在/WEB-INF/tags/下面的,要配置web.xml文件:加上配置:
<jsp-config> <taglib> <!--標簽庫的uri路徑即jsp頭文件中聲明<%@ taglib uri="/helloworldtaglib" prefix="mytag"%>的uri--> <taglib-uri>/helloworldtaglib</taglib-uri> <taglib-location>/WEB-INF/tags/helloworld.tld</taglib-location> </taglib> </jsp-config>
輸出結果:
后面有其他的用到的,繼續更新》。。。。。