题目
编写两个 Tag 文件 Rect.tag 和 Circle.tag。Rect.tag 负责计算并显示矩形的面积,Circle.tag 负责计算并显示圆的面积。编写一个 JSP 页面 lianxi6.jsp,该 JSP 页面使用Tag标记调用 Rect.tag 和Circle.tag。调用 Rect.tag 时,向其传递矩形的两个边的长度;调用 Circle.tag 时,向其传递圆的半径。
项目结构
代码
lianxi6.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib tagdir="/WEB-INF/tags/3.6" 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>
<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>
Rect.tag
<%@ tag pageEncoding="utf-8" %>
<%@ 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="utf-8" %>
<%@ 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));
}
%>