首先是计算矩形面积的Rect.tag
<%@ tag pageEncoding="gb2312" %>
<%@ attribute name = "sideA" required = "true" %>
<%@ attribute name = "sideB" required = "true" %>
<%@ variable name-given="area1" variable-class="java.lang.Double" scope="AT_END" %>
<%!
public double getArea(double a,double b){
if(a>0&&b>0){
double area = a*b;
return area;
}else{
return -1;
}
}
%>
<% try{
double a = Double.parseDouble(sideA);
double b = Double.parseDouble(sideB);
double result = getArea(a,b);
jspContext.setAttribute("area1",new Double(result));
}
catch(Exception e){
jspContext.setAttribute("area1",new Double(-1.0));
}
%>
然后是计算圆形面积的Circle.tag
<%@ tag pageEncoding="gb2312" %>
<%@ attribute name="radius" required="true" %>
<%@ variable name-given="area2" variable-class="java.lang.Double" scope="AT_END" %>
<%!
public double getArea(double r){
if(r>0){
double area=Math.PI * r * r;
return area;
}else{
return -1;
}
}
%>
<% try{
double r=Double.parseDouble(radius);
double result1=getArea(r);
jspContext.setAttribute("area2",new Double(result1));
}
catch(Exception e){
jspContext.setAttribute("area2",new Double(-1.0));
}
%>
最后就是JSP页面linxin6.jsp
<%@ page contentType = "text/html;charset = gb2312" %>
<%@ taglib tagdir = "/WEB-INF/tags" prefix="computer" %>
<HTML>
<BODY>
<form action="" method=get name=form>
<h3>计算矩形面积:</h3>
<table>
<tr>
<td>长:</td>
<td><input type="text" name="a"></td>
</tr>
<tr>
<td>宽:</td>
<td><input type="text" name="b"></td>
</tr>
</table>
<h3>计算圆形面积:</h3>
<table>
<tr>
<td>半径:</td>
<td><input type="text" name="r"></td>
</tr>
</table>
<br> <input type="submit" value="计算" name=submit>
</form>
<% String a=request.getParameter("a");
String b=request.getParameter("b");
String r=request.getParameter("r");
if(a==null||b==null||r==null){
a="0";
b="0";
r="0";
}
if(a.length()>0&&b.length()>0&&r.length()>0){
%> <computer:Rect sideA="<%=a%>" sideB="<%=b%>"/>
<computer:Circle radius="<%=r%>"/>
<br> 矩形面积:
<br> <%=area1 %>
<br> 圆形面积:
<br> <%=area2 %>
<% }
%>
</BODY>
</HTML>
下面是运行结果