自定义标签的开发步骤

自定义标签的开发步骤:
1 类实现SimpleTag接口,该类叫标签处理对象
  //标签处理器或标签对象
 public class IpTag implements SimpleTag {
     private PageContext pageContext;
     //Web容器调用
     public IpTag(){
          System.out.println("IpTag()");
          System.out.println("创建IpTag : " + this.hashCode());
     }
     //Web容器调用
     public void setJspContext(JspContext pc) {
          System.out.println("setJspContext()");
          //强转成子类
          pageContext = (PageContext) pc;
     }
     //Web容器调用
     public void doTag() throws JspException, IOException {
          System.out.println("doTag()");
          //转成HttpServletRequest
          HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
          //取得客户端IP
          String ip = request.getRemoteAddr();
          //取得out对象
          JspWriter out = pageContext.getOut();
          //输出到浏览器
          out.write("<font color='red'><b>"+ip+"</b></font>");
     }

 
 2 在/WEB-INF/下,写一个*.tld标签描述文件,目的是通知JSP引擎自定义标签所对应的处理类
<?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>simple</short-name>(自定义标签的前缀)
     <uri>http://java.sun.com/jsp/jstl/simple</uri>(自定义标签都位于哪一个名称空间/自定义标签类位于哪个包)
     <tag>
          <name>ip</name>(自定义标签的名,不是前缀)
          <tag-class>cn.itcast.web.jsp.tag.IpTag</tag-class>(自定义标签对应的标签处理类的全路径)
          <body-content>empty</body-content>(自定义标签是否中空标签或是非空标签,
                                 empty表示空标签)


          <attribute>
                  <name>count</name>(属性名)
                  <required>true</required>(属性是否必须,true必须,false可选)
                  <rtexprvalue>true</rtexprvalue>(属性值是动态还是静态,true动态或静态,false只能是静态)
               <type>boolean</type>(属性类型,可选)
              </attribute>


     </tag>

</taglib>

  
3 在simple.jsp页面中使用自定义标签
 
<%@ page language="java" pageEncoding="UTF-8"%>
  <%@ taglib uri="http://java.sun.com/jsp/jstl/simple" prefix="simple"%>[注意,一定在声明]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
       客户端IP是(标签版):<simple:ip/>
  </body>
</html>

 

猜你喜欢

转载自q137681467.iteye.com/blog/2022452