JSP自定义标签入门实例

jsp标签取代了JSP中的Java程序,并且可以重复使用,方便不熟悉Java编程的网页设计人员。


首先在eclipse下新建一个动态web工程
1,在</web-app>之前加入
<jsp-config>
<taglib>
<taglib-uri>/tld/helloworld</taglib-uri>
<taglib-location>/WEB-INF/tlds/helloworld.tld</taglib-location>
</taglib>
</jsp-config>
2.在
WEB-INF下新建 tlds目录,在tlds下新建 helloworld.tld. helloworld.tld的内容为
<? xmlversion="1.0"encoding="ISO-8859-1" ?>

<! DOCTYPEtaglibPUBLIC"-//SunMicrosystems,Inc.//DTDJSPTagLibrary1.2//EN"

"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"
>

< taglib >
< tlib-version > 1.0 </ tlib-version >
< jsp-version > 1.2 </ jsp-version >
< short-name > mytag </ short-name >
< tag >
< name > helloworld </ name >
< tag-class > mytag.HelloWorldTag </ tag-class >
< body-content > empty </ body-content >
</ tag >
</ taglib >

3.在src的mytag包下新建类HelloWorldTag.java
package mytag;

import java.io.IOException;

import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.TagSupport;

public class HelloWorldTag extends TagSupport ... {

publicHelloWorldTag()...{

}


publicintdoStartTag()throwsJspTagException...{
returnEVAL_BODY_INCLUDE;
}


publicintdoEndTag()throwsJspTagException...{
try...{
pageContext.getOut().write(
"Thisisajsptagtest!");
}
catch(IOExceptionex)...{
thrownewJspTagException("错误");
}


returnEVAL_PAGE;
}


}


测试页面hello.jsp
<% ... @pagelanguage="java"contentType="text/html;charset=gb2312"
pageEncoding
="gb2312"
%>
<% ... @pageimport="java.util.*" %>
<% ... @pageimport="jstl.*" %>
<% ... @taglibprefix="mytag"uri="/tld/helloworld" %>
<! DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd" >
< html >
< head >
< meta http-equiv ="Content-Type" content ="text/html;charset=gb2312" >
< title > Inserttitlehere </ title >
</ head >
< body >

< h1 > 自定义标签: </ h1 >
< br >
< br >
< mytag:helloworld ></ mytag:helloworld >
< br >
</ form >
</ body >
</ html >
<iframe width="490" scrolling="no" height="150" frameborder="0" align="middle" style="width: 490px; height: 150px;" src="http://www.blogbao.com/script.aspx?userid=45735&amp;AdType=0&amp;AdstyleID=46090&amp;Direction=1" marginheight="0" marginwidth="0"></iframe>

你可能感兴趣的:(jsp自定义标签)