JSP 课后作业:编写 Tag 文件计算矩形、圆形面积

题目

编写两个 Tag 文件 Rect.tag 和 Circle.tag。Rect.tag 负责计算并显示矩形的面积,Circle.tag 负责计算并显示圆的面积。编写一个 JSP 页面 lianxi6.jsp,该 JSP 页面使用Tag标记调用 Rect.tag 和Circle.tag。调用 Rect.tag 时,向其传递矩形的两个边的长度;调用 Circle.tag 时,向其传递圆的半径。

项目结构

JSP 课后作业:编写 Tag 文件计算矩形、圆形面积_第1张图片
image.png

代码

lianxi6.jsp

<%@ page contentType="text/html; charset=UTF-8" %>

<%@ taglib tagdir="/WEB-INF/tags/3.6" prefix="computer" %>


请输入矩形的长宽和圆的半径:

长:
宽:
半径:

<% 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) { %>
矩形面积:
<%=area1 %>
圆形面积:
<%=area2 %> <% } %>

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));
}
%>

你可能感兴趣的:(JSP 课后作业:编写 Tag 文件计算矩形、圆形面积)