Java之 jstl 自定义标签的方法

1.写一个Java类

   我的路径是写再tag包中的一个 HelloTag类 

package tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
/*
 * 标签类
 * 		1.继承SimpleTagSupport
 * 		2.override  doTag方法
 * 		3.标签有哪些属性,标签类也得有对应的属性,属性名要一样,类型要匹配,并且有对应的set方法
 */
public class HelloTag extends SimpleTagSupport{
	private String info;
	private int qty;
	public HelloTag() {
		System.out.println("HelloTag running");
	}
	public void setInfo(String info) {
		System.out.println("HelloTag setInfo");
		this.info = info;
	}
	public void setQty(int qty) {
		System.out.println("HelloTag setQty");
		this.qty = qty;
	}
	@Override
	public void doTag() throws JspException, IOException {
		System.out.println("HelloTag doTag");
			/**
			 * 通过继承自SimpleTageSupport提供的方法来获得pageContext,pageContext
			 * 提供了获得其他所有隐含对象的方法
			 */
			PageContext pctx = (PageContext)getJspContext();
			for(int i =0;i<qty;i++){
			JspWriter out =  pctx.getOut();
			out.println(info+"<br>");
			}
			
	}
	
}

  定义一个.tld文件再 webapp下的WEB-INF文件夹中,实际就是xml

<?xml version="1.0" encoding="UTF-8" ?>

<taglib 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-jsptaglibrary_2_1.xsd"
    version="2.1">
    

          <tlib-version>1.1</tlib-version>
          <short-name>t</short-name>
     <uri>http//tedu.cn/mytag</uri>
     
     
       <tag>


    <name>date</name>
    <tag-class>tag.DateTag</tag-class>
        <!-- 
        body-content是用来告诉容器,标签有没有标签体,如果有,可以出现那些内容,
        empty:没有标签体
        scriptless:有标签体,但是,标签体里面不能够出现java代码
        JSP:有标签体 ,并且标签体里面允许出现java代码,但是只有复杂标签技术才支持这个值
     -->
    <body-content>empty</body-content>
   
    <attribute>

        <name>pattren</name>
        <!-- required 值为true,表示该属性必选 -->
        <required>true</required>
        <!-- retexprvalue 设置为true,表示该属性可以动态赋值,(比如可以使用el表达式来赋值) -->
        <rtexprvalue>true</rtexprvalue>
    </attribute>
 
  </tag>
  </taglib>

 

  使用:

<%@ page contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http//tedu.cn/mytag" prefix="t"%>  <!-- 引入 -->
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<t:hello info="Hello Kitty" qty="${1+8 }"></t:hello> <!-- 使用 -->
</body>
</html>

 

posted on 2019-01-11 14:20  Top丶赵立全  阅读(369)  评论(0编辑  收藏  举报

导航