标签:
1、编写一个实现Tag接口的java类
package TagDemo; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.Tag; import java.io.IOException; public class ViewIPTag implements Tag { private PageContext pageContext; @Override public void setPageContext(PageContext pageContext) { this.pageContext = pageContext; } @Override public void setParent(Tag tag) { } @Override public Tag getParent() { return null; } @Override public int doStartTag() throws JspException { System.out.println("调用doStartTag方法"); HttpServletRequest request= (HttpServletRequest) pageContext.getRequest(); JspWriter writer=pageContext.getOut(); String ip=request.getRemoteAddr(); try { writer.write(ip); } catch (IOException e) { e.printStackTrace(); } return 0; } @Override public int doEndTag() throws JspException { System.out.println("调用doEndTag方法"); return 0; } @Override public void release() { System.out.println("调用release方法"); } }
2、编写tld标签库文件,tld文件必须放在WEB-INF文件夹或其子文件夹下,此文件是用来对标签处理器类进行描述
<?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>自定义标签</description> <tlib-version>1.0</tlib-version> <short-name>SDT</short-name> <uri>/sefDefineTag</uri> <tag> <description>输出客户端地址</description> <name>viewIPTag</name> <tag-class>TagDemo.ViewIPTag</tag-class> <body-content>empty</body-content> </tag> </taglib>
taglib标签库标签简述
description:对标签库描述信息
tlib-version:标签库版本
short-name:标签库名称
uri:标签库唯一标识,jsp就是通过uri引用标签的,uri必须以/开头,后面随便写,只要名称唯一;如下面引用<%@taglib prefix="sdt" uri="/sefDefineTag" %>
tag:taglib标签库中可以包含多个自定义标签,每个tag对应一个自定义标签
description:对当前标签的描述
name:定义一个名称,Jsp中通过这个名称引用标签处理器类
tag-class:对应的标签处理器类
body-content:定义标签体
3、在Jsp文件中测试
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="sdt" uri="/sefDefineTag" %> <html> <head> <title></title> </head> <body> IP:<sdt:viewIPTag/> </body> </html>
Jsp中就可以引入标签库,使用prefix可以设置标签库别名,标签使用方式就是<标签库别名:标签名称>
标签:
原文地址:http://www.cnblogs.com/hujiapeng/p/5781184.html