第一步,標籤實現
- package com.dadao.tag;
- import java.io.IOException;
- import javax.servlet.jsp.JspException;
- import javax.servlet.jsp.tagext.SimpleTagSupport;
- public class OutParamTag extends SimpleTagSupport {
- private Integer num;
- @Override
- public void doTag() throws JspException, IOException {
- this.getJspContext().setAttribute("result", num.intValue()*num.intValue());
- this.getJspBody().invoke(null);
- }
- public void setNum(Integer num) {
- this.num = num;
- }
- }
第二步,修改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>
- <tag>
- <description></description>
- <name>sqt</name>
- <tag-class>com.dadao.tag.OutParamTag</tag-class>
- <body-content>scriptless</body-content>
- <variable><!-- 輸出參數 -->
- <name-given>result</name-given>
- </variable>
- <attribute><!-- 定義輸入參數 -->
- <name>num</name>
- <required>true</required><!-- 該參數項是必須的 -->
- <rtexprvalue>true</rtexprvalue><!-- 允許腳本表達式作爲其值 -->
- </attribute>
- </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/>
- <hr>
- <cy:sqt num="25">
- ${result}
- </cy:sqt>
- </body>
- </html>