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());