JSP自定义标签

tld文件

<?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">
    <description>A tag library</description>
    <tlib-version>1.0</tlib-version>
    <short-name>util</short-name>
    <uri>http://localhost:8080/shop/util</uri>
    <tag>
<description>Outputs Hello, World</description>
        <name>timer</name>
<tag-class>com.apq.hellotag.HelloTag</tag-class>
         <!-- JSP: 可以包含java、html代码 -->
         <!-- empty: 不能包含内容 -->
         <!-- scriptless: 不能包含java代码,但可以包含EL代码或者动作代码 -->
         <!-- tagdependent: 由标记决定 -->

<body-content>[JSP,empty,scriptless,tagdependent]</body-content>
    </tag>
   
</taglib>


JSP文件
<%@ taglib prefix="util" uri="http://localhost:8080/shop/util" %>
<util:timer>
<%
	for(int i = 0; i < 100000000; i++){}
%>
<div>html</div>
</util:timer>

<%
	out.println("<br>end!!!!");
%>


JAVA文件
package com.apq.hellotag;

import java.io.IOException;

import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class HelloTag extends TagSupport {
	long start;
	long end;
	
	@Override
	public int doStartTag() throws JspException {
		start = System.currentTimeMillis();
		return EVAL_BODY_INCLUDE;
	}

	@Override
	public int doEndTag() throws JspException {
		end = System.currentTimeMillis();
		long elapse = end - start;
		
		try {
			JspWriter out = pageContext.getOut();
			out.println(elapse + "ms");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return EVAL_PAGE;
	}

}

输出结果:
html
79ms
end!!!!

给标记添加属性

给标记打包
拷贝class文件(带包的)到某个文件夹下面,新建文件夹 META-INF, 把xxx.tld文件拷贝进去
jar -cvf mytags.jar *
以后用的时候放到WEB-INF/lib下面就可以了

你可能感兴趣的:(java,html,jsp,Web,servlet)