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的內容為
<?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/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;
}
public int doStartTag() throws JspTagException...{
return EVAL_BODY_INCLUDE;
}
public int doEndTag() throws JspTagException...{
try...{
pageContext.getOut().write("This is a jsp tag test!");
}catch(IOException ex)...{
throw new JspTagException("錯誤");
}
return EVAL_PAGE;
}
}
測試頁面hello.jsp
import java.io.IOException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.TagSupport;
public class HelloWorldTag extends TagSupport...{ public HelloWorldTag()...
<%...@ page language="java" contentType="text/html; charset=gb2312"
< pageEncoding="gb2312"%>
<%...@ page import="java.util.*"%>
<%...@ page import="jstl.*"%><%...@ taglib prefix="mytag" uri="/tld/helloworld"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Insert title here</title>
</head>
<body>
<h1>自定義標簽:</h1>
<br>
<br>
<mytag:helloworld></mytag:helloworld>
<br>
</form>
</body>
</html>