自定义标签库开发

1.使用标签输出客户机IP

    1.1编写一个是实现tag接口的Java类(继承TagSupport类)

	public class ViewTag extends TagSupport {

	@Override
	public int doEndTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
		JspWriter out = this.pageContext.getOut();
		String ip=request.getRemoteAddr();
    	try {
			out.write(ip);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return super.doEndTag();
	}
	}

    1.2.在tld文件中对标签处理器类进行描述(tld文件的位置WEB-INF下,可以抄tomcat webapps下文件

 <?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>viewtag</short-name>
    <uri>www.scong.cn</uri>
    <tag>
        <name>viewIP</name>
        <tag-class>cn.scong.web.tag.ViewTag</tag-class>
        <body-content>empty</body-content>
    </tag>
     </taglib>

    1.3.在jsp页面中导入和使用自定义标签

	<%@ taglib uri="www.scong.cn" prefix="viewtag" %>
    <body>
      		您的ip是:
       		<viewtag:viewIP/>
      </body>

2.自定义标签功能扩展

    2.1控制jsp页面某一部分内容是否执行  

    2.2控制整个jsp页面是否执行  

    2.3控制jsp页面内容重复执行  

    2.4修改jsp页面内容输出  

    2.5 tld文件中的四种标签体类型: empty JSP scriptless tagdepentend

    例1:控制jsp页面某一部分内容是否执行(Tag接口)

	public class TagDemo1 extends TagSupport {

	@Override
	public int doStartTag() throws JspException {
		
		return Tag.SKIP_BODY;
		//return Tag.EVAL_BODY_INCLUDE;
	}
	}

tld:

 <tag>
        <name>demo1</name>
        <tag-class>cn.scong.web.tag.TagDemo1</tag-class>
        <body-content>JSP</body-content>
    </tag>

jsp:

      <body>
      	<viewtag:demo1>
    		This is my JSP page. 
    	</viewtag:demo1>
      </body>

    例2.控制整个jsp页面是否执行(Tag接口)

	public class TagDemo2 extends TagSupport{

	@Override
	public int doEndTag() throws JspException {
		
		return Tag.SKIP_PAGE;
	}
	}

tld:

    <tag>
        <name>demo2</name>
        <tag-class>cn.scong.web.tag.TagDemo2</tag-class>
        <body-content>empty</body-content>
    </tag>

jsp:

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ taglib uri="www.scong.cn" prefix="viewtag"%>
    <viewtag:demo2/>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>  
    <title>用标签控制整个页面是否输出</title>
      </head>
      
      <body>
    This is my JSP page. <br>
      </body>
    </html>

    例3:控制jsp页面内容重复执行(IterationTag )

	public class TagDemo3 extends TagSupport {
	
	int x=10;
	
	@Override
	public int doStartTag() throws JspException {
		
		return Tag.EVAL_BODY_INCLUDE;
	}

	@Override
	public int doAfterBody() throws JspException {
		x--;
		if (x>0) {
			return IterationTag.EVAL_BODY_AGAIN;
		}else {
			return IterationTag.SKIP_BODY;
		}
	}
	}

tld:

    <tag>
        <name>demo3</name>
        <tag-class>cn.scong.web.tag.TagDemo3</tag-class>
        <body-content>JSP</body-content>
    </tag>

jsp:

      <body>
      	<viewtag:demo3>
       	 	This is my JSP page. <br>
    	</viewtag:demo3>
      </body>

    例4:修改jsp页面内容输出 (BodyTag)

	public class TagDemo4 extends BodyTagSupport {
	@Override
	public int doStartTag() throws JspException {
		
		return BodyTag.EVAL_BODY_BUFFERED;
	}

	@Override
	public int doEndTag() throws JspException {
		BodyContent bc = this.bodyContent;
		String content = bc.getString();
		content=content.toUpperCase();
		JspWriter out = this.pageContext.getOut();
		try {
			out.write(content);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return Tag.EVAL_PAGE;
	}	
	}

tld:

    </tag>
        <tag>
        <name>demo4</name>
        <tag-class>cn.scong.web.tag.TagDemo4</tag-class>
        <body-content>JSP</body-content>
    </tag>

jsp:

      <body>
      	<viewtag:demo4>
    		my name is scong
      	</viewtag:demo4>
      </body>

    JSP2.0使用SimpleTatSupport扩展标签库功能

    例1:使用simpletagsupport控制jsp页面某一部分内容是否执行

    public class SimpleTagDemo1 extends SimpleTagSupport {
    
    	@Override
    	public void doTag() throws JspException, IOException {
    		JspFragment jf = this.getJspBody();
    		//jf.invoke(this.getJspContext().getOut());
    	}
    }

tld:

	<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>simpletag</short-name>
    <uri>www.song.cn</uri>
    <tag>
        <name>demo1</name>
        <tag-class>cn.scong.web.simpletag.SimpleTagDemo1</tag-class>
        <body-content>scriptless</body-content>
    </tag>
 	</taglib>

jsp:

      <body>
     	 <simpletag:demo1>
      	  	This is my JSP page. <br>
     	 </simpletag:demo1>
      </body>

    例2:使用simpletagsupport控制jsp页面内容重复执行

	public class SimpleTagDemo2 extends SimpleTagSupport {

	@Override
	public void doTag() throws JspException, IOException {
		JspFragment jf = this.getJspBody();
		for (int i = 0; i <5; i++) {
			//jf.invoke(this.getJspContext().getOut());
			jf.invoke(null);
		}
	}
	}

tld:

    <tag>
        <name>demo2</name>
        <tag-class>cn.scong.web.simpletag.SimpleTagDemo2</tag-class>
        <body-content>scriptless</body-content>
    </tag>

jsp:

      <body>
      	<simpletag:demo2>
    		This is my JSP page. <br>
    	</simpletag:demo2>
      </body
    例3:使用simpletagsupport修改jsp页面内容
public class SimpleTagDemo3 extends SimpleTagSupport {

	@Override
	public void doTag() throws JspException, IOException {
		JspFragment jf = this.getJspBody();
		//jf.invoke(this.getJspContext().getOut());
		StringWriter sw = new StringWriter();
		jf.invoke(sw);
		String content = sw.toString();
		content=content.toUpperCase();
		this.getJspContext().getOut().write(content);
	}
	}

tld:

    <tag>
        <name>demo3</name>
        <tag-class>cn.scong.web.simpletag.SimpleTagDemo3</tag-class>
        <body-content>scriptless</body-content>
    </tag>

jsp:

      <body>
    	<simpletag:demo3>
       	 		This is my JSP page. <br>
    	</simpletag:demo3>
      </body>

    例4:使用simpletagsupport控制整个jsp是否输出

	public class SimpleTagDemo4 extends SimpleTagSupport {

	@Override
	public void doTag() throws JspException, IOException {
		throw new SkipPageException();
	}
	}

tld:

    <tag>
        <name>demo4</name>
        <tag-class>cn.scong.web.simpletag.SimpleTagDemo4</tag-class>
        <body-content>empty</body-content>
    </tag>

jsp:

<simpletag:demo4/>

3.开发带属性的标签

    3.1.在自定义标签类中定义属性,并设置set方法

	public class SimpleTagDemo5 extends SimpleTagSupport {

	private int count;
	private Date date;
	
	public void setCount(int count) {
		this.count = count;
	}
	
	public void setDate(Date date) {
		this.date = date;
	}
		
	@Override
	public void doTag() throws JspException, IOException {
		JspFragment jf = this.getJspBody();
		//jf.invoke(this.getJspContext().getOut());
		this.getJspContext().getOut().write(date.toLocaleString());
		for (int i = 0; i < count; i++) {
			jf.invoke(null);			
		}
	}
	}

    3.2.在tld文件中,定义属性名称及属性标签

    <tag>
        <name>demo5</name>
        <tag-class>cn.scong.web.simpletag.SimpleTagDemo5</tag-class>
        <body-content>scriptless</body-content>
        <attribute>
        	<name>count</name>
        	<required>true</required>
        	<rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
        	<name>date</name>
        	<required>true</required>
        	<rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>

    3.3.在jsp文件中使用标签

      	<simpletag:demo5 count="90" date="<%=new Date() %>">
      	 	 This is my JSP page. <br>
     	</simpletag:demo5>

4.嵌套标签的使用

    原理:定义一个父标签,在父标签类中定义个属性保存子标签状态。

ChooseTag类:

	public class ChooseTag extends SimpleTagSupport {

	private boolean isdo;

	public boolean isIsdo() {
		return isdo;
	}

	public void setIsdo(boolean isdo) {
		this.isdo = isdo;
	}

	@Override
	public void doTag() throws JspException, IOException {
		this.getJspBody().invoke(null);
	}	
	}

WhenTag类:

	public class WhenTag extends SimpleTagSupport{

	private boolean test;

	public void setTest(boolean test) {
		this.test = test;
	}

	@Override
	public void doTag() throws JspException, IOException {
		ChooseTag parent = (ChooseTag) this.getParent();
		if (test&&!parent.isIsdo()) {
			this.getJspBody().invoke(null);
			parent.setIsdo(true);
		}
	}
	}

OtherwiseTag类:

	public class OtherwiseTag extends SimpleTagSupport {

	@Override
	public void doTag() throws JspException, IOException {
		ChooseTag parent = (ChooseTag) this.getParent();
		if (!parent.isIsdo()) {
			this.getJspBody().invoke(null);
			parent.setIsdo(true);
		}
	}	
	}

example.tld:

	<?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>e</short-name>
    <uri>/example</uri>
    <tag>
        <name>choose</name>
        <tag-class>cn.scong.web.example.ChooseTag</tag-class>
        <body-content>scriptless</body-content>
    </tag>
    <tag>
        <name>when</name>
        <tag-class>cn.scong.web.example.WhenTag</tag-class>
        <body-content>scriptless</body-content>
        <attribute>
        	<name>test</name>
        	<required>true</required>
        	<rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>
    <tag>
        <name>otherwise</name>
        <tag-class>cn.scong.web.example.OtherwiseTag</tag-class>
        <body-content>scriptless</body-content>
    </tag>
    </taglib>

jsp:

      <body>
    	<e:choose>
    		<e:when test="${user==null }">
    			aaaaa
    		</e:when>
    		<e:otherwise>
    			bbbb
    		</e:otherwise>
    	</e:choose>
      </body>

5.自定义foreach标签

	public class ForeachTag extends SimpleTagSupport{

	private Object items;
	private String var;
	public void setItems(Object items) {
		this.items = items;
	}
	public void setVar(String var) {
		this.var = var;
	}
	@Override
	public void doTag() throws JspException, IOException {
		
		List list = (List) items;
		Iterator it = list.iterator();
		while (it.hasNext()) {
			String value = (String) it.next();
			this.getJspContext().setAttribute(var, value);
			this.getJspBody().invoke(null);
		}
	}	
	}

tld:

    <tag>
        <name>foreach</name>
        <tag-class>cn.scong.web.example.ForeachTag</tag-class>
        <body-content>scriptless</body-content>
        <attribute>
        	<name>items</name>
        	<required>true</required>
        	<rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
        	<name>var</name>
        	<required>true</required>
        	<rtexprvalue>false</rtexprvalue>
        </attribute>
    </tag>

jsp:

      <body>
    <%
    	List list = new ArrayList();
    	list.add("aaa");
    	list.add("bbb");
    	list.add("ccc");
    	list.add("ddd");
    	request.setAttribute("list", list);
     %>
     
    	 <e:foreach var="str" items="${list }">
     		${str }<br/>
    	 </e:foreach>
      </body>

6.模拟sum公司foreach标签开发

	public class ForeachTag2 extends SimpleTagSupport {

	private Object items;
	private String var;

	public void setItems(Object items) {
		this.items = items;
		if (items instanceof Collection) {
			collection = (Collection) items;
		}

		if (items instanceof Map) {
			Map map = (Map) items;
			collection = map.entrySet();
		}

		if (items instanceof Object[]) {
			Object object[] = (Object[]) items;
			collection = Arrays.asList(object);

		}
		
		if (items.getClass().isArray()) {
			this.collection = new ArrayList();
			int length = Array.getLength(items);
			for (int i = 0; i <length; i++) {
				Object value =Array.get(items, i);
				this.collection.add(value);
			}
		}

	}

	public void setVar(String var) {
		this.var = var;
	}

	private Collection collection;

	@Override
	public void doTag() throws JspException, IOException {
		
		Iterator it = this.collection.iterator(); 
		while (it.hasNext()) {
			Object value = it.next();
			this.getJspContext().setAttribute(var, value);
			this.getJspBody().invoke(null);
		}
	}
	}

tld:

    </tag>
        <tag>
        <name>foreach2</name>
        <tag-class>cn.scong.web.example.ForeachTag2</tag-class>
        <body-content>scriptless</body-content>
        <attribute>
        	<name>items</name>
        	<required>true</required>
        	<rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
        	<name>var</name>
        	<required>true</required>
        	<rtexprvalue>false</rtexprvalue>
        </attribute>
    </tag>

jsp:

      <body>
    <%
    	List list = new ArrayList();
    	list.add("aaa");
    	list.add("bbb");
    	list.add("ccc");
    	list.add("ddd");
    	request.setAttribute("list", list);
     %>
     
     <e:foreach2 var="str" items="${list }">
     	${str }<br/>
     </e:foreach2>
     <br>-----------------------------------------------<br>
     <%
		Map map = new HashMap();
		map.put("1", "aaa"); 
		map.put("2", "bbb");
		map.put("3", "ccc");  
		request.setAttribute("map", map);  	
      %>
      <e:foreach2 items="${map }" var="entry">
      		${entry.key }=${entry.value }<br/>
      </e:foreach2>
      <br>-----------------------------------------------<br>
      
      <%
      		Integer num[] = {1,2,3,4,5,6};
      		request.setAttribute("num", num);
       %>
       <e:foreach2 items="${num }" var="i">
       		${i }<br/>
       </e:foreach2>
       <br>-----------------------------------------------<br>
       <%
      		double arr[] = {1,2,3,4,5,6};
      		request.setAttribute("arr", arr);
       %>
       <e:foreach2 items="${arr }" var="i">
       		${i }<br/>
       </e:foreach2>
      </body>

7.html转译标签

    filter方法在F:\Program Files\apache-tomcat-7.0.67\apache-tomcat-7.0.67\webapps\examples\WEB-INF\classes\util下可以找到

	public class HtmlFliterTag extends SimpleTagSupport {

	@Override
	public void doTag() throws JspException, IOException {
		
		StringWriter sw  =new StringWriter();
		JspFragment jf = this.getJspBody();
		jf.invoke(sw);
		String content = sw.getBuffer().toString();
		content = filter(content);
		this.getJspContext().getOut().write(content);
	}
	
	public static String filter(String message) {

        if (message == null)
            return (null);

        char content[] = new char[message.length()];
        message.getChars(0, message.length(), content, 0);
        StringBuilder result = new StringBuilder(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
            case '<':
                result.append("<");
                break;
            case '>':
                result.append(">");
                break;
            case '&':
                result.append("&");
                break;
            case '"':
                result.append(""");
                break;
            default:
                result.append(content[i]);
            }
        }
        return (result.toString());

    }
	}

tld:

    <tag>
        <name>htmlfilter</name>
        <tag-class>cn.scong.web.example.HtmlFliterTag</tag-class>
        <body-content>scriptless</body-content>
    </tag

jsp:

      <body>
    	<e:htmlfilter>
    		<a href="">点我</a>
    	</e:htmlfilter>
      </body>

8.将自定义标签库打包成jar包

    1.新建Java project

    2.在src目录下将原来的自定义标签库类文件(包)拷贝一份

    3.在工程目录下新建一个META-INF目录,将tld文件拷贝到此目录下

    4.将工程以jar包形式输出,取消勾选工程文件

猜你喜欢

转载自blog.csdn.net/sconghw/article/details/80973954