JSP--矩形(圆)面积计算器

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib tagdir="/WEB-INF/tags" prefix="Util" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>练习六</title>
</head>
<body>
<form action="" method= get>
	<table>
		<th>矩形(圆)面积计算器</th>
		<tr>
		<td>输入高a(半径r):</td>
		<td><input type="text" name ="a" placeholder="请输入..."/></td>
		</tr>
		
		<tr>
		<td>输入宽b:</td>
		<td><input type="text" name ="b" placeholder="请输入..."/></td>
		</tr>
		
	</table>
	<br><input type="submit" value = "提交"></input>
	</form>
	
	<%  String a = request.getParameter("a");
		String b = request.getParameter("b");
		if (a == null||b == null) {
			a = "0";
			b = "0";
		}
		if (a.length()>0&&b.length()>0){%>
	<Util:Rect sideA="<%=a%>" sideB="<%=b%>"/>
	<br><%=area1%>
	<%}
		if (a.length()>0&&b.length()==0){
		String r = request.getParameter("a");
		%>
	<Util:Circle radius="<%=r%>"/>
	<br><%=area2%>
	<%}%>
</body>
</html>

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

Ciecle.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--矩形(圆)面积计算器
  • 圆计算
    JSP--矩形(圆)面积计算器

心得

  1. Tag文件与Jsp文件区别: Tag文件用于数据处理,jsp文件用于数据显示;
  2. Tag标记使用:
    • 声明: <%@ taglib tagdir="/WEB-INF/tags" prefix=“前缀”%>
    • 使用: <tags:Rect /> 务必":"间不留空格
    • WEB-INF/tags: 务必小写;
    • 前缀: 用于区别不同文件下的同名tag文件;