JSP頁面如何訪問標籤中定義的變數-使用實現
阿新 • • 發佈:2019-02-06
首先定義標籤類:
其中message為變數名
package testtag;import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
publicclass TestVar extends TagSupport {
@Override
publicint doStartTag() throws JspException {
try{
JspWriter out
out.println("in doStartTag");
pageContext.setAttribute("message", "hello");
}catch(Exception e){
e.printStackTrace();
}
return(SKIP_BODY);
}
}
定義TLD檔案
其中<name-from-attribute>id</name-from-attribute>說明變數名可分局自定義標籤的id屬性動態設定
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>c_rt</short-name>
<uri>http://fff/t</uri>
<display-name>JSTL core RT</display-name>
<description>JSTL 1.0 core library</description
<tag>
<name>testvar</name>
<tag-class>testtag.TestVar</tag-class>
<body-content>empty</body-content>
<description>
test var
</description>
<variable>
<name-from-attribute>id</name-from-attribute>
<variable-class>String</variable-class>
<declare>true</declare>
<scope>AT_BEGIN</scope>
</variable>
<attribute>
<name>id</name>
<required>true</required>
</attribute>
</tag>
</taglib>
jsp:
此處<testvar:testvar id="message"/>設定變數名稱為message
<%@ page language="java" contentType="text/html; charset=GB18030"pageEncoding="GB18030"%>
<%@ taglib uri="testtag" prefix="testvar"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<testvar:testvar id="message"/>
${message}
</body>
</html>
執行結果如下:
in doStartTag hello ,可見,可以打印出在標籤類中變數message的內容hello