Tag标记的使用
一个JSP页面通过Tag标记来调用一个Tag文件
格式
<% @taglib tagdir="标记库的位置" prefix="前缀">
引入标记库就可以使用带前缀的Tag标记调用相应的Tag文件
使用Tag标记调用oddNumberSum.tag计算100之内的奇数和
<% @ page contentType="text/html"%> <% @page pageEncoding="utf-8"%> <% @ taglib tagdir="WEB-INF/tags" prefix="computer"%> <HTML> <body bgcolor=cyan> <h1>调用Tag文件计算100内奇数的和:</h1> <computer:oddNumberSum/><%--使用Tag标记--%> </body> </HTML>
attribute指令
在Tag中通过使用attribute指令让使用它的JSP页面文件传递需要的数据
<% @ attribute name="对象名字" required="true"|"false" type="对象的类型"%>
attribute中name属性是必须的
type没有使用指定类型,那么对象类型的默认值为java.lang.String
使用Tag标记向所调用的Tag文件中name指定的对象传递一个引用:
<前缀:Tag 文件名字 对象名字="对象的引用"/>
例如,JSP页面使用Tag标记(假设标记的前缀为computer)调用myTag.tag:
<computer:myTag result="new Double(3.124)"/>
使用Tag标记调用triangle文件,并且向triangle.tag传递三角形三边的长度:
example3_2.jsp:
<% @ page contentType="text/html" %> <% @ page pageEncoding="utf-8"%> <% @ taglib tagdir="/WEB-INF/tags/example2"prefix="getTriangleArea"%> <HTML> <body bgcolor=yellow> <p style="font-family:宋体;font-size:36;color:blue"> <%--使用Tag标记:--%> <getTriangleArea:triangle sideA="15"sideB="16"sideC="20"/> </p> </body> </HTML>
triangle.tag
<% @ tag pageEncoding="utf-8"> <% @ attribute name="sideA" required="true"%> <% @ attribute name="sideB" required="true"%> <% @ attribute name="sideC" required="true"%> <% ! pubilc String getArea(double a,double b,double c) if(a+b>c&&a+c>b&&b+c>a){ double p=(a+b+c)/2.0; double area=Math.sqrt(p*(p-a)*(p-b)*(p-c)); String result =String.format("%.2f".area); return"<br>三角形面积(小数点保留两位):"+result; } else return("<br>+a+","+b+","+c+"不能构成一个三角形,无法计算面积"); } %> <% out.println("<BR>三边:"+sideA+","+sideB+","+sideC); double a=Double.parseDouble(sideA); double b=Double.parseDouble(sideB); double c=Double.parseDouble(sideC); out.println(getArea(a,b,c)); %>
variable指令
<% @ variable name-given="对象名" variable-class="对象类型" scope="有效范围"%>
使用调用该Tag文件的JSP页面动态地向其传递数据
variable指令中属性name-given的值就是Tag文件返回给JSP页面对象
对象的返回:
Tag文件只有将对象的名字及其引用存储到jspContext中,JSP页面才可以使用该对象:
<% @ variable name-given="time" variable-class="java.time.LocalDate" scope="AT_END"%>
为JSP页面返回名字是LocalDate的对象,那么Tag文件中必须让jspContext调用
setAttribute("对象名",对象的引用);
方法存储名字是time的对象及该对象的引用
jspContext.setAttribute("time",LocalDate.now());