標籤:重寫 round 標示 路徑 esc 上下文 des 其他 extend
學到了一個簡單的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>
輸出結果:
後面有其他的用到的,繼續更新》。。。。。
一個簡單的jsp自訂標籤