jsp自定义标签之ifelse与遍历自定义标签示例

  第一个示例:

  简单的jsp自定标签获取内容:

  首先创建一个jsp实例类然后继承SimpleTagSupport类

  然后实现父类的doTag()方法

  在这个方法里获取标签体里的内容this.getJspBody();

  返回的是JspFragment 类,根据这个类对象调用invoke(this.getJspContext().getOut());

  这个方法里面也可以写空,所表达的意思也是输出到浏览器;

  

复制代码 代码如下:

  public class SimpleDmeo1 extends SimpleTagSupport {

  @Override

  public void doTag() throws JspException, IOException {

  JspFragment js =this.getJspBody();

  js.invoke(null);

  }

  }

  然后在写tld文件标签库描述文件,和jsp文件,这些都较为简单

  如果不想执行某个内容就抛出异常

  throw new skipPageException();和面内容就不会显示

  接下来是一个带属性的jsp自定义标签文件

  

复制代码 代码如下:

  public class SimpleDmeo1 extends SimpleTagSupport {

  private int counts;

  public void setCounts(int counts) {

  this.counts = counts;

  }

  @Override

  public void doTag() throws JspException, IOException {

  JspFragment js =this.getJspBody();

  for(int i=0;i<counts;i++){ //循环获取

  js.invoke(null);

  }

  }

  }

  <description>A tag library exercising SimpleTag handlers.</description>

  <tlib-version>1.0</tlib-version>

  <short-name>c</short-name>前缀名

  <uri>http://www.csdn.com</uri>

  <tag>

  <name>demo</name>

  <tag-class>com.csdn.simple.SimpleDmeo1</tag-class>

  <body-content>scriptless</body-content>

  <attribute>

  <name>counts</name>

  <required>true</required>

  <rtexprvalue>true</rtexprvalue>

  </attribute>

  </tag>

  然后再jsp文件 中写出内容;

  

复制代码 代码如下:

  <hbsi:demo counts="3">aaaaaaa<br/></hbsi:demo> //输出三编

  JspFragment js = this.getJspBody();

  StringWriter jw = new StringWriter();

  js.invoke(jw);

  String s = jw.toString().toUpperCase();

  JspWriter out =this.getJspContext().getOut();

  for(int i=0;i<counts2;i++){

  out.print(s);

  }

  }

  这是转成大写的代码,其他的都一致;

  关于if else的代码,太多,我放到资源里了,有必要的话可以下载下来,仅供参考。