zoukankan      html  css  js  c++  java
  • JSP自定义标签(3)


    八、SimpleTagSupport类


    在JSP2.0后,为了简化标签开发的难度,就可以使用SimpleTagSupport进行开发;


    1.开发一般标签


    注意点:

    (1)需要继承SimpleTagSupport类;

    (2)实现public void doTag()throws JspException,IOException;

    (3)super.getJspContext().getOut().write("....");   进行输出;

    (4)在SimpleTagSupport中,tld中的<body-content>内容不能为JSP,如果标签体不为空,则只能为scriptless


    代码:

    SimpleTagSupportDemo.java

    package org.tagext;
    import javax.servlet.jsp.tagext.*;
    import javax.servlet.jsp.*;
    import java.io.*;
    public class SimpleTagSupportDemo extends SimpleTagSupport{
    	private String name;
    	public String getName(){
    		return name;
    	}
    	public void setName(String name){
    		this.name = name;
    	}
    	public void doTag()throws JspException,IOException{
    		super.getJspContext().getOut().write("<h3>"+name+"</h3>");
    	}
    }


    2.开发迭代标签


    通过super.getJspBody().invoke(null);能够执行标签体内容;

    SimpleTagSupportDemo.java
    package org.tagext;
    import javax.servlet.jsp.tagext.*;
    import javax.servlet.jsp.*;
    import java.io.*;
    import java.util.*;
    public class SimpleTagSupportDemo extends SimpleTagSupport{
    	private String name;
    	private String id;
    	public String getName(){
    		return name;
    	}
    	public void setName(String name){
    		this.name = name;
    	}
    	public String getId(){
    		return id;
    	}
    	public void setId(String id){
    				this.id = id;
    	}
    	public void doTag()throws JspException,IOException{
    		Object value = super.getJspContext().getAttribute(name,PageContext.PAGE_SCOPE);
    		Iterator<String> iter = ((List<String>)value).iterator();
    		while(iter.hasNext()){
    			super.getJspContext().setAttribute(id,iter.next());
    			super.getJspBody().invoke(null);
    		}
    
    	}
    }

    综合看来,SimpleTagSupport比起前面的TagSupport,BodyTagSupport,简单了许多,不需要任何返回值;


    九、常见问题


    1.区分是否有标签体

    <xiazdong:hello name="">

    </xiazdong:hello>

    是属于有标签体的,只是标签体为空;

    <xiazdong:hello name=""/>为标签体为空;



    作者:xiazdong
    出处:http://blog.xiazdong.info
    本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
  • 相关阅读:
    Redis常用操作命令
    redis-sentinel.conf配置项详解
    Kafka常用命令
    go modules的使用姿势
    GO语言密码加解密(bcrypt)
    ssh-copy-id 秘钥分发报错
    k8s 命令提示
    算法与数据结构(持续更新)
    【spring】 @PostConstruct注解
    Spring Boot 整合Redis
  • 原文地址:https://www.cnblogs.com/xiazdong/p/3058119.html
Copyright © 2011-2022 走看看