JSP中開發自定義標籤步驟:
以在JSP頁面輸出"hello world"爲例:
第一步,標籤底層實現.
代碼如下:
- package com.dadao.tag;
- import java.io.IOException;
- import javax.servlet.jsp.JspException;
- import javax.servlet.jsp.tagext.SimpleTagSupport;
- public class HelloWorldTag extends SimpleTagSupport {
- @Override
- public void doTag() throws JspException, IOException {
- this.getJspContext().getOut().write("hello world");
- }
- }
第二步,撰寫標記庫的tld文件:
在/WEB-INF目錄下新建一個taglib/cy.tld文件.內容如下:
- <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">
- <description>oper tag library</description>
- <display-name>display text</display-name>
- <tlib-version>1.0</tlib-version>
- <short-name>cy</short-name>
- <uri>http://mytaglib/chenyang</uri>
- <tag>
- <description>chenyang's custom display message tag</description>
- <name>sayHello</name>
- <tag-class>com.dadao.tag.HelloWorldTag</tag-class>
- <body-content>empty</body-content>
- </tag>
- </taglib>
第三步,在web.xml中的配置,
- <jsp-config>
- <taglib>
- <taglib-uri>/WEB-INF/taglib/cy.tld</taglib-uri>
- <taglib-location>http://mytaglib/chenyang</taglib-location>
- </taglib>
- </jsp-config>
第四步,撰寫JSP文件,代碼如下:
- <%@ page language="java" pageEncoding="UTF-8"%>
- <%@ taglib prefix="cy" uri="http://mytaglib/chenyang" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>My JSP 'index.jsp' starting page</title>
- </head>
- <body>
- <cy:sayHello/>
- </body>
- </html>