JSP Custom Tags:
1. Inherit simpletagsupport, rewrite Dotag ().
2. Configure the **.tld file under web-inf/
3.JSP page Introduction to Custom Tags: <%@ taglib uri= "* * *" prefix= "s"%>
Custom Label Demo implementation: On the JSP page, save the object in Pagecontext.setattribute () and use the label to output all methods, member variables, and values of the object.
Testtag.java:
PackageMyTag;Importjava.io.IOException;ImportJava.io.Writer;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;ImportJavax.servlet.jsp.tagext.SimpleTagSupport; Public classTesttagextendssimpletagsupport{PrivateString obj;//with attribute tags the corresponding setter and getter methods must be provided for each property PublicString getobj () {returnobj; } Public voidsetobj (String obj) { This. obj =obj; } Public voidDotag ()throwsioexception{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);//Private members can also access 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> <!--Define label names - <name>Info</name> <!--defining label Handling classes - <Tag-class>MyTag. Testtag</Tag-class> <!--define the label body as empty - <body-content>Empty</body-content> <!--Configuration Label Properties: 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 " pageencodingImport=" 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" > Pagecontext.setattribute (new Date ()); %><b><s:hello/></b><b><s:info obj= "Date"/></b></body>
Jsp_demo: Custom Labels