javaweb带属性的自定义标签

时间:2022-04-22 19:42:42

带属性的自定义标签:

1.先在标签处理器中定义setter方法,建议把所有的属性类型都设置为String类型。

package com.javaweb.tag;

import java.io.IOException;

import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.JspTag;
import javax.servlet.jsp.tagext.SimpleTag; public class HelloSimpleTag implements SimpleTag {
private String value;
private String count; public void setCount(String count) {
this.count = count;
} public void setValue(String value) {
this.value = value;
} //标签体的逻辑实际应该编写到此方法中
@Override
public void doTag() throws JspException, IOException {
JspWriter out=pageContext.getOut();
int c=0;
c=Integer.parseInt(count);
for(int i=0;i<c;i++){
out.print((i+1)+":"+value);
out.print("<br>");
}
} @Override
public JspTag getParent() {
System.out.println("getParent");
return null;
} @Override
public void setJspBody(JspFragment arg0) {
System.out.println("setJspBody");
}
private PageContext pageContext;
//JSP引擎调用,把代表jsp页面的PageContext对象传入
@Override
public void setJspContext(JspContext arg0) {
System.out.println(arg0 instanceof PageContext);
this.pageContext=(PageContext)arg0;
} @Override
public void setParent(JspTag arg0) {
System.out.println("setParent");
} }

2.在tld文件中描述属性

<attribute>
<!-- 属性名,需和标签处理器类的setter方法定义的属性相同 -->
<name>value</name>
<!-- 该属性是否被必须 -->
<required>true</required>
<!-- rtexprvalue:runtime expression value 当前属性是否可以接受运行时表达式的动态值 -->
<rtexprvalue>true</rtexprvalue>
</attribute> <attribute>
<name>count</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>

3.在jsp页面中使用属性

属性名同tld文件中定义的名字。

<koala:hello value="koala" count="8"/>

wx搜索“程序员考拉”,专注java领域,一个伴你成长的公众号!

javaweb带属性的自定义标签