您可以将各种属性与自定义标签一起使用。要接受属性值,自定义标记类需要实现setter方法,与JavaBean setter方法相同,如下所示-
package com.nhooo; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class HelloTag extends SimpleTagSupport { private String message; public void setMessage(String msg) { this.message = msg; } StringWriter sw = new StringWriter(); public void doTag() throws JspException, IOException { if (message != null) { /* Use message from attribute */ JspWriter out = getJspContext().getOut(); out.println( message ); } else { /* use message from the body */ getJspBody().invoke(sw); getJspContext().getOut().println(sw.toString()); } } }
该属性的名称为“ message”,因此setter方法为setMessage()。现在让我们使用<attribute>元素将此属性添加到TLD文件中,如下所示-
<taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>Example TLD with Body</short-name> <tag> <name>Hello</name> <tag-class>com.nhooo.HelloTag</tag-class> <body-content>scriptless</body-content> <attribute> <name>message</name> </attribute> </tag> </taglib>
让我们遵循JSP的message属性,如下所示:
<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%> <html> <head> <title>A sample custom tag</title> </head> <body> <ex:Hello message = "This is custom tag" /> </body> </html>
这将产生以下结果-
This is custom tag