1.创建web项目three,新建包sun.moon,新建rect.java文件
2.WebRoot下的WEB-INF下新建tlds文件夹,新建my.tld文件
3.新建MyJsp.jsp文件
4.rect.java文件代码如下
package sun.moon;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
public class rect extends SimpleTagSupport {
private String Length;
private String Width;
public void doTag() throws JspException,IOException{
getJspContext().getOut().write("Length="+this.Length+"," +
"Width="+this.Width+getArea(Double.parseDouble(Length),Double.parseDouble(Width)));
}
public void setLength(String Length)
{
this.Length=Length;
}
public void setWidth(String Width)
{
this.Width=Width;
}
public String getArea(double a,double b)
{
if(a>0&&b>0)
{
double area=a*b;
return "<br>长方形的面积:"+area;
}else{
return("<br>"+a+","+b+","+"不能构成一个长方形,无法计算面积");
}
}
}
5.my.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">
<description>
简单标记自定义标记库
</description>
<tlib-version>1.0</tlib-version>
<short-name>my</short-name>
<uri>http://myWeb.com/jsp/myTags</uri>
<tag>
<description>Outputs a colored tile</description>
<name>my1</name>
<tag-class>sun.moon.rect</tag-class>
<body-content>empty</body-content>
<attribute>
<name>length</name>
<required>true</required>
</attribute>
<attribute>
<name>width</name>
<required>true</required>
</attribute>
</tag>
</taglib>
6.MyJsp.jsp文件代码如下
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="WEB-INF/tlds/my.tld" prefix="me" %>
<html>
<body>
<me:my1 length="10" width="10"/>
</body>
</html>
7.浏览器显示效果