开发Struts 2 自定义标签三步曲:
1.定义标签
public class AddressTag extends ComponentTagSupport {
//定义你JSP页面传来的标签设置的属性
private String id;
//此方法就是获得一个基本类的Component对象(需自定义生成)
@Override
public Component getBean(ValueStack valueStack, HttpServletRequest request, HttpServletResponse response) {
AddressComponent addressComponent=new AddressComponent(valueStack, request);
..................................
return addressComponent;
}
}
2.创建Component子类
public class AddressComponent extends Component {
private String id;
//重写start方法 通过writer输出字符串。
public boolean start(Writer writer) {
boolean result = super.start(writer);
//从值栈中获取属性值
String id = getStack().findString(id);
writer.write("<div>"+id+"Hello World"+"</div>");
return result;
}
}
3.建.tld 文件
1 <taglib> 2 <tlib-version>2.2.3</tlib-version> 3 <jsp-version>1.2</jsp-version> 4 <short-name>my</short-name> 5 <uri>/address</uri> 6 <display-name>"jason time tab"</display-name> 7 <tag> 8 <name>address</name> 9 <tag-class>com.AddressTag</tag-class> 10 <body-content>empty</body-content> 11 <attribute> 12 <name>id</name> 13 <required>false</required> 14 <rtexprvalue>true</rtexprvalue> 15 </attribute> 16 </tag> 17 </taglib>
OK, 页面打开时,load入<%@ taglib prefix="" uri="/WEB-INF/tlds/address.tld" %>;
<w:address id="XXXX"/>