jsp中自定义标签用法实例分析
本文实例讲述了jsp中自定义标签用法。分享给大家供大家参考。具体如下:
这里简单的写了一个自定义标签,自己定义标签的好处就是在jsp页面中可以使用自己定义的功能,完全与Java代码分离
1.tld文件如下:
首先是要写×.tld文件,当项目随着服务器启动的时候,会检查项目中有没有*tld文件。
写的tld文件
<?xmlversion="1.0"encoding="UTF-8"?> <taglibxmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <!--定义版本--> <tlib-version>1.0</tlib-version> <!--定义名字--> <short-name>apsliyuan</short-name> <!--定义uri--> <uri>http://my.oschina.net/aps</uri> <!--定义自己的类--> <tag> <!--name就是在jsp中显示的标签名字,<aps:hellowTag/>--> <name>hellowTag</name> <!--自己写的标签类的完整路径--> <tag-class>cn.itcast.apsliyuan.tag.HellowtTag</tag-class> <!--jsp中主题中是不是要显示内容,有四个属性,如果为empty的话。在jsp页面中标签就不能定义自己的内容了,否则会报Servlet.service() forservletjspthrewexceptionorg.apache.jasper.JasperException:/index.jsp(12,8) AccordingtoTLD,tagaps:hellowTagmustbeempty,butisnot异常 --> <body-content>JSP</body-content> </tag> <!-- 这里没有写属性,有时间补上 --> <tag> <name>ApsliyuanTag</name> <tag-class>cn.itcast.apsliyuan.tag.ApsliyuanTag</tag-class> <body-content>JSP</body-content> </tag> </taglib>
2.自定义标签类java代码如下:
//自定义标签的类
packagecn.itcast.apsliyuan.tag;
importjava.io.IOException;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjavax.servlet.jsp.JspException;
importjavax.servlet.jsp.JspWriter;
importjavax.servlet.jsp.tagext.TagSupport;
publicclassHellowtTagextendsTagSupport{
/**
*
*/
privatestaticfinallongserialVersionUID=1781703371130382609L;
@Override
publicintdoStartTag()throwsJspException{
//TODOAuto-generatedmethodstub
JspWriterout=pageContext.getOut();
SimpleDateFormatformat=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");
try{
out.print(format.format(newDate()));
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
returnEVAL_BODY_INCLUDE;
}
@Override
publicintdoEndTag()throwsJspException{
//TODOAuto-generatedmethodstub
JspWriterout=pageContext.getOut();
try{
out.print("<br/><hr/>标签执行完毕了");
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
returnEVAL_PAGE;
}
}
3.jsp引入自己定义标签代码如下:
//jsp中引入自己定义的标签 <%@pagelanguage="java"contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <%@tagliburi="http://my.oschina.net/aps"prefix="aps"%> <%@tagliburi="http://java.sun.com/jsp/jstl/core"prefix="c"%> <!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>index.jsp</title> </head> <body> 现在的时间是:<aps:hellowTag></aps:hellowTag><br/> <hr/> 我爱的人是:<aps:ApsliyuanTag/> </body> </html>
4.TagSupport代码如下:
//看看TagSupport中的源代码,这个是适配器模式
publicclassTagSupportimplementsIterationTag,Serializable{
publicstaticfinalTagfindAncestorWithClass(Tagfrom,
//TCKsignaturetestfailswithgenerics
@SuppressWarnings("unchecked")
Classklass){
booleanisInterface=false;
if(from==null||
klass==null||
(!Tag.class.isAssignableFrom(klass)&&
!(isInterface=klass.isInterface()))){
returnnull;
}
for(;;){
Tagtag=from.getParent();
if(tag==null){
returnnull;
}
if((isInterface&&klass.isInstance(tag))||
klass.isAssignableFrom(tag.getClass()))
returntag;
else
from=tag;
}
}
/**
*Defaultconstructor,allsubclassesarerequiredtodefineonly
*apublicconstructorwiththesamesignature,andtocallthe
*superclassconstructor.
*
*ThisconstructoriscalledbythecodegeneratedbytheJSP
*translator.
*/
publicTagSupport(){}
/**
*Defaultprocessingofthestarttag,returningSKIP_BODY.
*
*@returnSKIP_BODY
*@throwsJspExceptionifanerroroccurswhileprocessingthistag
*
*@seeTag#doStartTag()
*/
publicintdoStartTag()throwsJspException{
returnSKIP_BODY;
}
/**
*DefaultprocessingoftheendtagreturningEVAL_PAGE.
*
*@returnEVAL_PAGE
*@throwsJspExceptionifanerroroccurswhileprocessingthistag
*
*@seeTag#doEndTag()
*/
publicintdoEndTag()throwsJspException{
returnEVAL_PAGE;
}
/**
*Defaultprocessingforabody.
*
*@returnSKIP_BODY
*@throwsJspExceptionifanerroroccurswhileprocessingthistag
*
*@seeIterationTag#doAfterBody()
*/
publicintdoAfterBody()throwsJspException{
returnSKIP_BODY;
}
//Actionsrelatedtobodyevaluation
/**
*Releasestate.
*
*@seeTag#release()
*/
publicvoidrelease(){
parent=null;
id=null;
if(values!=null){
values.clear();
}
values=null;
}
/**
*Setthenestingtagofthistag.
*
*@paramtTheparentTag.
*@seeTag#setParent(Tag)
*/
publicvoidsetParent(Tagt){
parent=t;
}
/**
*TheTaginstancemostcloselyenclosingthistaginstance.
*@seeTag#getParent()
*
*@returntheparenttaginstanceornull
*/
publicTaggetParent(){
returnparent;
}
/**
*Settheidattributeforthistag.
*
*@paramidTheStringfortheid.
*/
publicvoidsetId(Stringid){
this.id=id;
}
/**
*Thevalueoftheidattributeofthistag;ornull.
*
*@returnthevalueoftheidattribute,ornull
*/
publicStringgetId(){
returnid;
}
/**
*Setthepagecontext.
*
*@parampageContextThePageContext.
*@seeTag#setPageContext
*/
publicvoidsetPageContext(PageContextpageContext){
this.pageContext=pageContext;
}
/**
*AssociateavaluewithaStringkey.
*
*@paramkThekeyString.
*@paramoThevaluetoassociate.
*/
publicvoidsetValue(Stringk,Objecto){
if(values==null){
values=newHashtable<String,Object>();
}
values.put(k,o);
}
/**
*Getathevalueassociatedwithakey.
*
*@paramkThestringkey.
*@returnThevalueassociatedwiththekey,ornull.
*/
publicObjectgetValue(Stringk){
if(values==null){
returnnull;
}else{
returnvalues.get(k);
}
}
/**
*Removeavalueassociatedwithakey.
*
*@paramkThestringkey.
*/
publicvoidremoveValue(Stringk){
if(values!=null){
values.remove(k);
}
}
/**
*Enumeratethekeysforthevalueskeptbythistaghandler.
*
*@returnAnenumerationofallthekeysforthevaluesset,
*ornulloranemptyEnumerationifnovalueshavebeenset.
*/
publicEnumeration<String>getValues(){
if(values==null){
returnnull;
}
returnvalues.keys();
}
//privatefields
privateTagparent;
privateHashtable<String,Object>values;
/**
*Thevalueoftheidattributeofthistag;ornull.
*/
protectedStringid;
//protectedfields
/**
*ThePageContext.
*/
protectedPageContextpageContext;
}
doStartTag的返回值
在doStartTag返回的值决定的body部分的数据如何显示。
两个返回值:
0–SKIP_BODY–常量。不显示body。
1-EVAN_BODY_INCLUDE;包含body部分的数据,正常显示。
3:在doEndTag也有两个返回值
决定后面的页面部分是否显示:
SKIP_PAGE:不再显示后面的页面部分。
EVAL_PAGE:显示后面的page部分。
希望本文所述对大家的JSP程序设计有所帮助。