Struts自定义标签

首先定义一个类,继承BodyTagSupport 类,并实现其方法,在这里定义了两个属性,
通过EvalHelper.evalString的方法将标签中的名称和值放到属性中;
public class DisplayDescTag extends BodyTagSupport {

// parameters
private String list;

private String code;

public int doStartTag() throws JspException {
String _code = EvalHelper.evalString("code", code, this, pageContext);
List _list =
(List) ExpressionEvaluatorManager.evaluate(
"list",
list,
List.class,
this,
pageContext);

String value = "";
for (Iterator iter = _list.iterator(); iter.hasNext();) {
LabelValueBean obj = (LabelValueBean) iter.next();
if (obj.getValue().equals(_code)) {
value = obj.getLabel();
break;
}
}
try {
JspWriter out = pageContext.getOut();
out.print(value);
} catch (Exception ex) {
throw new JspTagException(ex.getMessage());
}
return EVAL_PAGE;
}

public void release() {
super.release();
}

/**
* @return
*/
public String getCode() {
return code;
}

/**
* @return
*/
public String getList() {
return list;
}

/**
* @param string
*/
public void setCode(String string) {
code = string;
}

/**
* @param string
*/
public void setList(String string) {
list = string;
}

}
增加TLD文件如下:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
  "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>1.2</jsp-version>
  <short-name>es</short-name>
  <uri>...</uri>
  <display-name>e-sales taglib</display-name>
  <description>e-sales taglib</description>

  <tag>
    <name>displayDesc</name>
    <tag-class>com.cignacmc.web.taglib.DisplayDescTag</tag-class>
    <body-content>JSP</body-content>
    <description>
       Display the description according to code and list
    </description>
    <attribute>
        <name>list</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <name>code</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>

</taglib>
在页面上我们通过将TLD文件进行引入,方式为:
<%@ taglib uri="/WEB-INF/tld/e-sales.tld" prefix="es" %>

这样我们在页面上就可以调用标签中的方法了:
<es:displayDesc code="${insured.ssnType}" list="${ssnTypeList}"/>
到这里整个标签就可以正常工作了!

你可能感兴趣的:(jsp,Web,xml,struts,sun)