JSTL(JSP Standard Tag Library ,JSP标准标签库)是一个不断完善的开放源代码的JSP标签库,是由apache的jakarta小组来维护的。JSTL只能运行在支持JSP1.2和Servlet2.3规范的容器上,如tomcat 4.x。在JSP 2.0中也是作为标准支持的。
下面,让我们来看看自定义JSTL标签步骤。
第一步:导入要用到的两个包:jstl.jar standard.jar。
第二步:写一个java类,继承SimpleTagSupport类,并重写doTag()方法。
package tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class MessageTag extends SimpleTagSupport{
private String info;//标签的属性
private int num;//标签的属性
public String getInfo() {
return info;
}
public MessageTag() {
System.out.println("constructor...");
}
public void setInfo(String info) {
System.out.println("setInfo..." + info);
this.info = info;
}
public int getNum() {
return num;
}
public void setNum(int num) {
System.out.println("setNum:" + num);
this.num = num;
}
@Override
public void doTag() throws JspException, IOException {
System.out.println("doTag...");
PageContext pc = (PageContext)getJspContext();
JspWriter out = pc.getOut();
for(int i=0;i<num;i++){
out.println(info+"<br/>");
}
}
}
第二步:在WEB-INF文件夹中新建一个.tld文件,在.tld文件中,描述标签。
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.1</tlib-version>
<short-name>tag1</short-name>
<uri>http://www.yuck.com.cn/mytag1</uri>
<tag>
<name>msg</name>
<tag-class>tag.MessageTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>info</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>num</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
<!--注:rtexprvalue的全称是 Run-time Expression Value,它用于表示是否可以使用JSP表达式.
当在<attribute>标签里指定<rtexprvalue>true</rtexprvalue>时,表示该自定义标签的某属性的值可以直接指定或者通过动态计算指定.
当在<attribute>标签里指定<rtexprvalue>false</rtexprvalue>时, 表示该自定义标签的某属性的值只能直接指定.
-->
第三步:在jsp页面中,使用taglib命令引入.tld文件。
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib prefix="tag1" uri="http://www.yuck.com.cn/mytag1" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body style="font-size:30pt;">
hello<br/>
<tag1:msg info="hello" num="100"/>
</body>
</html>