日期:2014-05-16  浏览次数:20328 次

jsp自定义标签自学笔记(一)
jsp的自定义标签库有着较好的代码复用性,而且可以使整个页面简洁、美观。使用起来非常方便。下面就动手实现一个简单的“hello world”标签。

1、实现自定义标签可以继承javax.servlet.jsp.tagext.TagSupport类,重写该类方法。代码如下:
package fox.tags.hello;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class HelloTag extends TagSupport{
	
	@Override
	public int doStartTag() throws JspException {
		JspWriter out=this.pageContext.getOut();
		try{
			out.write("hello world !");//页面中显示的内容
		}catch(IOException e){
			e.printStackTrace();
		}
		return this.SKIP_BODY;//不包含主体内容
	}
	
}



2、编写hello.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>shortname</short-name>
 <tag>
  <name>hello</name>
  <tag-class>fox.tags.hello.HelloTag</tag-class>
 </tag>
</taglib>


3、配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <jsp-config>
  	<taglib>
  		<taglib-uri>/hello-tags</taglib-uri>
  		<taglib-location>/WEB-INF/tld/hello.tld</taglib-location>
  	</taglib>
  </jsp-config>
</web-app>


4、在页面中引用自定义标签库
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f" uri="/hello-tags"  %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
    <f:hello></f:hello>
  </body>
</html>