如何实现自定义jsp标签

1、实现标签类,继承自TagSupport,实现doStartTag()方法。

public class AliasTag extends TagSupport {
 private String memberid;
 @Override
 public int doStartTag() throws JspException {
  JspWriter out = this.pageContext.getOut();
  try{
   MemberService memberService = (MemberService)ServiceLocator.getBean("MemberService");
   if(memberid != null && !memberid.equals("")){
    Member member = memberService.findById(Long.valueOf(memberid));
    if(member != null)
     out.print(member.getAlias() == null ? "--" : member.getAlias());
    else
     out.println("--");
   }else{
    out.println("--");
   }
  }catch(Exception e){
   System.out.println("根据memberid获取别名异常!");
   e.printStackTrace();
  }
  return SKIP_BODY;
 }

 public String getMemberid() {
  return memberid;
 }

 public void setMemberid(String memberid) {
  this.memberid = memberid;
 }
}

 

2、编辑tld文件。

<?xml version="1.0" encoding="UTF-8"?>
<!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>ftt</short-name>
 <tag>
  <name>getNameById</name>
  <tag-class>cn.itour.basic.tag.FlowTaskTag</tag-class>
  <body-content>JSP</body-content>
  <attribute>
   <name>manageId</name>
   <required>true</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
 </tag>
 <tag>
  <name>getAliasByMemberid</name>
  <tag-class>cn.itour.basic.tag.AliasTag</tag-class>
  <body-content>JSP</body-content>
  <attribute>
   <name>memberid</name>
   <required>true</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
 </tag>
</taglib>

 

3、在web.xml页面注册tld文件。

<jsp-config>

 <taglib>
   <taglib-uri>/flowtask</taglib-uri>
   <taglib-location>/WEB-INF/flowtask.tld</taglib-location>
  </taglib>
 </jsp-config>

 

4、在jsp页面使用标签。

            <%@ taglib prefix="ft" uri="/flowtask" %>

            <td align="center">
              <ft:getAliasByMemberid memberid="${record.menberid}" />
             </td>

你可能感兴趣的:(jsp自定义标签)