JSP的開發是在HTML代碼中嵌入了大量的Java代碼,可是這樣一來會使得JSP頁面中充滿了Java程序,修改或維護起來很是的不方便,html
定義一個簡單的標籤----空標籤java
要想實現一個標籤,能夠直接繼承javax.servlet.jsp.tagext.TagSupport類,若是要定義的標籤內沒有標籤體,則直接覆寫TagSupport類中的doStartTag()方法便可。web
進行第一個hello程序sql
定義標籤的操做類 —— HelloTag.javaapache
package com.oumyye.tagdemo; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; public class HelloTag extends TagSupport { @Override public int doStartTag() throws JspException { JspWriter out = super.pageContext.getOut(); // 取得頁面輸出流對象 try { out.println("<h1>Hello World!!!</h1>"); // 進行頁面輸出 } catch (Exception e) { // 此處產生異常,須要處理 e.printStackTrace(); } return TagSupport.SKIP_BODY; // 沒有標籤體 } }
定義標籤描述文件 —— /WEB-INF/hellotab.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_1.xsd" version="2.1"> <tlib-version>1.0</tlib-version> <!-- 表示標籤庫的版本 --> <short-name>firsttag</short-name> <!-- 爲標籤庫在TLD中的描述名稱 --> <tag> <name>hello</name> <!-- 表示標籤在JSP中的使用名稱 --> <tag-class> com.oumyye.tagdemo.HelloTag </tag-class> <!-- 表示這個標籤所指向的class文件 --> <body-content>empty</body-content> <!-- 表示標籤體內容爲空 --> </tag> </taglib>
編寫JSP頁面並調用標籤 —— hellotag.jsptomcat
<%@ page contentType="text/html;charset=UTF-8"%> <%@ taglib prefix="mytag" uri="/WEB-INF/hellotag.tld"%> <html> <head> <title> 偶my耶</title> </head> <body> <h1><mytag:hello/></h1> <!-- 訪問標籤--> </body> </html>
web.xml配置app
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <jsp-config> <taglib> <taglib-uri>http://www.helloweenvsfei.com/tags</taglib-uri> <taglib-location>/WEB-INF/hellotag.tld</taglib-location> </taglib> </jsp-config> </web-app>
JSTL簡介:JSTL(JSP Standard Tag Library,JSP標準標籤庫)是一個開放源代碼的標籤組件,由Apache的Jakarta小組開發,能夠直接從http://tomcat.apache.org/taglibs/下載 ,下載來的JSTL.是以jar包的形式存在的,直接將此Jar包保存在WEB-INF/lib目錄之中,以後能夠直接經過WINRAR工具打開此JAR包,而且將裏面的META-INF文件夾中的幾個主要標籤配置文件:c.tld、fmt.tld、fn.tld、sql.tld、x.tld保存在WEB-INF文件夾之中jsp