JSP自定义标签简单入门教程
在sun官方文档上有下面这样一段话。
官方文档声明
publicinterfaceSimpleTag extendsJspTag InterfacefordefiningSimpleTagHandlers. SimpleTagHandlersdifferfromClassicTagHandlersinthatinsteadofsupportingdoStartTag()anddoEndTag(),theSimpleTaginterfaceprovidesasimpledoTag()method,whichiscalledonceandonlyonceforanygiventaginvocation.Alltaglogic,iteration,bodyevaluations,etc.aretobeperformedinthissinglemethod.Thus,simpletaghandlershavetheequivalentpowerofBodyTag,butwithamuchsimplerlifecycleandinterface. Tosupportbodycontent,thesetJspBody()methodisprovided.ThecontainerinvokesthesetJspBody()methodwithaJspFragmentobjectencapsulatingthebodyofthetag.Thetaghandlerimplementationcancallinvoke()onthatfragmenttoevaluatethebodyasmanytimesasitneeds. ASimpleTaghandlermusthaveapublicno-argsconstructor.MostSimpleTaghandlersshouldextendSimpleTagSupport.
生存周期及调用流程
Thefollowingisanon-normative,briefoverviewoftheSimpleTaglifecycle.RefertotheJSPSpecificationfordetails.
Anewtaghandlerinstanceiscreatedeachtimebythecontainerbycallingtheprovidedzero-argsconstructor.Unlikeclassictaghandlers,simpletaghandlersarenevercachedandreusedbytheJSPcontainer.
ThesetJspContext()andsetParent()methodsarecalledbythecontainer.ThesetParent()methodisonlycallediftheelementisnestedwithinanothertaginvocation.
Thesettersforeachattributedefinedforthistagarecalledbythecontainer.
Ifabodyexists,thesetJspBody()methodiscalledbythecontainertosetthebodyofthistag,asaJspFragment.Iftheactionelementisemptyinthepage,thismethodisnotcalledatall.
ThedoTag()methodiscalledbythecontainer.Alltaglogic,iteration,bodyevaluations,etc.occurinthismethod.
ThedoTag()methodreturnsandallvariablesaresynchronized.
简单标签使用小案例
必知必会:简单标签也是一个标签,所以声明的过程也Tag的一样,同样是三步。
1、建继承SimpleTag类的实现类,重写doTag方法
2、tld文件中进行严格的声明
3、jsp页面中taglib的命名空间及标签前缀的声明,然后进行调用自定义的简单标签
第一步:创建实现类:
packageweb.simpletag; importjava.io.IOException; importjava.io.StringWriter; importjavax.servlet.jsp.JspException; importjavax.servlet.jsp.PageContext; importjavax.servlet.jsp.SkipPageException; importjavax.servlet.jsp.tagext.JspFragment; importjavax.servlet.jsp.tagext.SimpleTagSupport; /** *控制标签体是否执行 *@authorSummer * */ publicclassBodyControllerextendsSimpleTagSupport{ static{ /* *简单标签整体的执行流程如下: *1.浏览器向web服务器发送请求,然后web服务器调用servlet(jsp) *2.complier解释器进行初始化工作,先是调用setJspContext方法,将pageContext对象传递进去 *3.然后是看看此标签的父标签,即setParent方法 *4.再就是调用doTag方法了吧?但是要知道doTag内部会使用JspFragment对象,所以就必须先得到它,因此应该是调用setJspBody(JspFragmentjspBody)方法 *5.最后是调用doTag方法,执行相关的代码逻辑 */ } /** *简单标签可以使用这一个方法实现所有的业务逻辑 */ @Override publicvoiddoTag()throwsJspException,IOException{ //代表标签体的对象 JspFragmentfragment=this.getJspBody(); //fragment.invoke(null);是指将标签中的内容写给谁,null代表浏览器 //1.修改标签体的内容 //fragment.invoke(null); //2.控制标签体内容的重复输出 //for(inti=1;i<=5;i++){ //fragment.invoke(null);//设置为null,默认为向浏览器输出 //} //3.修改标签体的内容 PageContextcontext=(PageContext)fragment.getJspContext(); StringWriterwriter=newStringWriter(); fragment.invoke(writer); Stringcontent=writer.getBuffer().toString(); this.getJspContext().getOut().write(content.toUpperCase()); //4.控制jsp页面的执行与否,只需要掌握一个原理即可 /* *SkipPageException-Ifthepagethat(eitherdirectlyorindirectly)invokedthis *tagistoceaseevaluation.ASimpleTagHandlergeneratedfromatag *filemustthrowthisexceptionifaninvokedClassicTagHandler *returnedSKIP_PAGEorifaninvokedSimpleTagHandlerthrew *SkipPageExceptionorifaninvokedJspFragmentthrewa *SkipPageException. */ //thrownewSkipPageException(); } }
在tld文件中进行相关约束项的配置:
<?xmlversion="1.0"encoding="UTF-8"?> <taglibxmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <description>JSTL1.1XMLlibrary</description> <display-name>JSTLXML</display-name> <tlib-version>1.1</tlib-version> <short-name>x</short-name> <uri>/simplesummer</uri> <!--控制标签体内容的的简单标签的自定义标签--> <tag> <name>BodyController</name> <tag-class>web.simpletag.BodyController</tag-class> <body-content>scriptless</body-content> </tag> </taglib>
第三步:在jsp页面中进行声明然后调用:
<%@pagelanguage="java"contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <%@tagliburi="/simplesummer"prefix="summer"%> <!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"> <title>用SimpleTag接口实现的控制标签体内容是否执行的测试页面</title> </head> <body> <summer:BodyController>Summer</summer:BodyController> </body> </html>
总结:
简单标签可以替代BodyTag接口完成同样的操作,但是有更加的简单和轻便
简单标签lifeCycle逻辑清晰,调用规则明确
使用相关流对象就可以完成对标签体的操控maniplate
以上就是本文的全部内容,希望对大家的学习有所帮助。