我的第一个taglib
taglib的好处:封装了那些重复使用的jsp,html,javascript代码,可以作为一个工具实现重用.
taglib分三个部分: java,tld,及jsp
java :
package com.davic.test.taglib;
import java.text.DecimalFormat;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class MetersToFeet extends BodyTagSupport { //1.重点,必须继承BodyTagSupport
private int precision = 2;
@Override
public int doAfterBody() throws JspException { // 重载方法(有多个方法,这是其中一个而已)
// TODO Auto-generated method stub
BodyContent body = this.getBodyContent(); // 得到body内容
try {
//实现标签逻辑
float meters = Float.valueOf(body.getString()).floatValue();
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(this.precision);
//response 回去主体
body.getEnclosingWriter().println(df.format(meters * 3.28));
} catch (Exception e) {
System.out.println("you have input invalid parameters");
} finally {
body = null;
}
return this.EVAL_PAGE;
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
this.precision = precision;
}
}
tld:
<?xml version="1.0" encoding="UTF-8"?>
<!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>2.2</tlib-version> <!--tlib版本-->
<jsp-version>1.2</jsp-version> <!--jsp版本-->
<short-name>******Taglib</short-name> <!--taglib名称-->
<uri>/marryfive</uri> <!--uri-->
<display-name>*****Taglib</display-name> <!--显示名称-->
<description><![CDATA[Marryfive JSP Taglib]]></description> <!--描述-->
<tag>
<name>m2f</name> <!--我定义tag的名称-->
<tag-class>com.davic.test.taglib.MetersToFeet</tag-class> <!--所用到的类-->
<body-content>jsp</body-content> <!--body内容-->
<attribute>
<name>precision</name> <!--taglib自定义的属性-->
<required>false</required> <!--该属性是否必须-->
</attribute>
</tag>
</taglib>
jsp:
<%@ taglib uri="/Web-INF/metric.tld" prefix="metric"%>
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html><head>
<title>"ding ni ge fei"</title>
</head>
<body>
<h1>testing metric tags</h1>
30 meters is <metric:m2f>30</metric:m2f> feet <br> //使用例子
<metric:m2f precision="4">37.98345</metric:m2f>fett<br>
</body>
</html>
然后在发布上web 服务器
打http://localhost:[your port]/[web-app]/[jsp.name]