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"
"/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" "/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>