首页 > 代码库 > 标签简介和开发第一个标签

标签简介和开发第一个标签

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@taglib uri="/itcast" prefix="itcast" %> 3  4 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 5 <html> 6   <head> 7      8     <title>My JSP ‘1.jsp‘ starting page</title> 9   10   </head>11   12   <body>13     您的IP是:14     <itcast:viewIP/>15   </body>16 </html>
JSP
 1 package cn.itcast.web.tag; 2  3 import java.io.IOException; 4  5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.jsp.JspException; 7 import javax.servlet.jsp.JspWriter; 8 import javax.servlet.jsp.tagext.TagSupport; 9 10 11 public class ViewIPTag extends TagSupport {12     13     public int doStartTag() throws JspException{14         15         HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();16         JspWriter out = this.pageContext.getOut();17         18         String ip = request.getRemoteAddr();19         try {20             out.print(ip);21         } catch (IOException e) {22             throw new RuntimeException();23         }24         25         return super.doStartTag();26     }27     28     29     30     31 32 }
ViewIPTag
 1 <?xml version="1.0" encoding="UTF-8" ?> 2  3  4 <taglib xmlns="http://java.sun.com/xml/ns/j2ee" 5     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" 7     version="2.0"> 8     <description>A tag library exercising SimpleTag handlers.</description> 9     <tlib-version>1.0</tlib-version>10     <short-name>itcast</short-name>11     <uri>/itcast</uri>12     13     <tag>14         <name>viewIP</name>15         <tag-class>cn.itcast.web.tag.ViewIPTag</tag-class>16         <body-content>empty</body-content>17     </tag>18    19   20   </taglib>
itcast.tld

1、编写一个实现tag接口的Java类

2、在tlb文件中对标签处理器类进行描述(tlb文件位置:WEB-INF下,可以抄)

3、在JSP页面中导入和使用自定义标签