自定义标签SimpleTagSupport的应用

一、 需要继承SimpleTagSupport类:


public class FormatString extends SimpleTagSupport {
 private String split;

 public void setSplit(String split) {
  this.split = split;
 }
 @Override
 public void doTag() throws JspException, IOException {
  JspFragment jf = this.getJspBody();
  StringWriter sw = new StringWriter();
  jf.invoke(sw); //写入到缓存
  String content = sw.toString(); //获取缓存数据
  String[] arrs = content.split("-");

  String head = arrs[3].substring(0, 3);
  String end = arrs[3].substring(3);
  arrs[3]=head + fillzero(end);
  String result = getstr(arrs);
 
  this.getJspContext().getOut().write(result); //写给浏览器
  
 }
 
 private String fillzero(String val){
  int len = val.length()-6; 
  StringBuffer sb = new StringBuffer();
  if(len<15){
   for(int i=len;i<15;i++){
    sb.append(0);
   }
  }
  sb.append(val);
  return sb.toString();
 }
 private String getstr(String[] arr){
  StringBuffer sb = new StringBuffer();
  for(String s :arr){
   sb.append(s).append(this.split);
  }
  return sb.subSequence(0, sb.length()-1).toString();
 }


}

二、为该类写一个tld文件,放到src目录下。

<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
    <description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>simple</short-name>
    <uri>http://com.web.output.tag</uri>
 <tag>
  <name>format</name>
  <tag-class>com.FormatString</tag-class>
  <body-content>scriptless</body-content>  <!--  取值有四种,为empty,JSP,scriptless,tagdepentend  -->
  <attribute> 
     <name>split</name>
     <required>yes</required>
  </attribute>
  
 </tag> 
</taglib>

三、要在jsp界面引入自定义标签,然后通过别名tag就可以使用。

<%@taglib uri="http://com.web.output.tag" prefix="tag"%>

posted @ 2013-04-30 13:39  若 ♂ 只如初见  阅读(308)  评论(0编辑  收藏  举报