原因在於:
servlet 2.3的配置不需要<jsp-config>標籤的,
servlet 2.4容器中<taglib>需要在<jsp-config>中。
(實際上,區分就在web.xml一開時的<web-app version="2.5"...web-app_2_5.xsd裏,這裏的2.5就代表2.5的版本)
完整的例子是孫衛琴的《Tomcat與Java Web開發技術詳解》中的第二章:創建和發佈web應用中,2.2.7 部署JSP Tag Library。
在web應用中可以加入Tag Library(標籤庫)。Tag Library向用戶提供了自定義JSP標籤的功能。以下一個例子就是自定義了一個標籤庫mytaglib。將<mm:hello/>解析爲"hello"。
(1)編寫處理hello標籤的類HelloTag.java:
- package mypack;
- import java.io.PrintWriter;
- import javax.servlet.jsp.JspException;
- import javax.servlet.jsp.JspTagException;
- import javax.servlet.jsp.tagext.TagSupport;
- public class HelloTag extends TagSupport {
- public void HelloTag()
- { }
- //Method called when the closing hello tag is encountered
- public int doEndTag()throws JspException
- {
- try
- {
- pageContext.getOut().print("Hello");
- }catch(Exception e)
- {
- throw new JspTagException(e.getMessage());
- }
- //this tag does not support a Tag Body(僅僅是<mm:hello/>,無標籤體),so we return SKIP_BODY
- return SKIP_BODY;
- }
- public void release()
- {
- //Call the parent's release to release any resources used by the parent tag.This is just good practice for when you start creating hierarchies of tags
- super.release();
- }
- }
(2) 創建Tag Libraray的描述文件mytaglib.tld文件,在這個文件中定義mytaglib標籤庫和hello標籤。這個文件存放的位置爲/WEB-INF/mytaglib.tld。
- <?xml version="1.0" encoding="utf-8"?>
- <taglib>
- <tlibversion>1.0</tlibversion>
- <jspversion>1.1</jspversion>
- <shortname>mytaglib</shortname>
- <uri>/mytaglib</uri>
- <tag>
- <name>hello</name>
- <tagclass>mypack.HelloTag</tagclass>
- <bodycontent>empty</bodycontent>
- <info>Just Says Hello</info>
- </tag>
- </taglib>
(3)在web.xml文件中加入<taglib>元素:這裏會出錯,說不能識別<taglib>原因一開始已經講了。
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="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-app_2_5.xsd"> <jsp-config>-------------------
- 如果是servlet 2.4,這個標籤要加,否則不加也對
- <taglib>
- <taglib-uri>/mytaglib</taglib-uri>
- <taglib-location>/WEB-INF/mytaglib.tld</taglib-location>
- </taglib>
- </jsp-config>
- </web-app>
<taglib>中包含兩個屬性<taglib-uri>和<taglib-location>。<taglib-uri>指定Tag Library標示符;<taglib-location>指定Tag Library的描述文件tld的位置。
(4)在web應用中加入hello標籤(hello.jsp)
<%@ tablib prefix="mm" uri="/mytaglib"%>------這句必須,並且prefix的參數mm是隨便取的。
- <html>
- <head><title>helloapp</title></head>
- <body>
- <b><mm:hello/>:lin!</b>
- </body>
- </html>