首页 > 代码库 > Jsp_demo:自定义标签

Jsp_demo:自定义标签

Jsp自定义标签:

      1.继承SimpleTagSupport,重写doTag()。

      2.在WEB-INF/ 下配置**.tld文件

      3.Jsp页面引入自定义标签:<%@ taglib uri="***" prefix="s"%>

自定义标签demo实现:在jsp页面将对象存入pageContext.setAttribute(),使用标签输出该对象的所有方法,成员变量及值。

TestTag.java:

package mytag;import java.io.IOException;import java.io.Writer;import java.lang.reflect.Field;import java.lang.reflect.Method;import javax.servlet.jsp.tagext.SimpleTagSupport;public class TestTag extends SimpleTagSupport{    private String obj;//带属性标签必须为每个属性提供对应的 setter 和 getter 方法    public String getObj() {        return obj;    }    public void setObj(String obj) {        this.obj = obj;    }    public void doTag() throws IOException{        Writer out = getJspContext().getOut();        Object object=(Object)getJspContext().getAttribute(obj);        Class<?> c=object.getClass();        Field fields[]=c.getDeclaredFields();        for(Field f:fields ){                        f.setAccessible(true);//私有成员也能访问            try {                out.write(f.getName()+":"+f.get(object)+"</br>");            } catch (IllegalArgumentException | IllegalAccessException e) {                e.printStackTrace();            }        }        Method methods[]=c.getMethods();        for(Method m:methods){            out.write(m.toString()+"</br>");        }    }}

mytaglib.tld:

<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE taglib        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"        "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd"><taglib>  <tlib-version>1.0</tlib-version>  <jsp-version>1.2</jsp-version>  <short-name>mytaglib</short-name>  <uri>/mytaglib</uri>  <tag>    <!-- 定义标签名 -->    <name>info</name>    <!-- 定义标签处理类 -->    <tag-class>mytag.TestTag</tag-class>    <!-- 定义标签体为空 -->    <body-content>empty</body-content>    <!-- 配置标签属性:driver -->    <attribute>        <name>obj</name>         <required>true</required>        <fragment>true</fragment>    </attribute>     </tag></taglib>

test.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ page import="mytag.User,java.util.*" %>    <%@ taglib uri="/mytaglib" prefix="s" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><%    pageContext.setAttribute("date", new Date());%><b><s:hello/></b><b><s:info obj="date"/></b></body></html

技术分享

 

Jsp_demo:自定义标签