自定義Tag文件封裝步驟與示例

相同的顏色就是對應的名稱。 html

1.在項目WebRoot/WEB_INF,下新建 HtmlTag.tld 文件 java

<?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" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
 
 
       <tlib-version> 1.0</tlib-version >
       <jspversion> 1.1</jspversion >
       <shortname> yao</shortname >
       <uri> http://com.yao/tags/html</uri >
      
       <tag>
             <name> TextTag</name >
             <tagclass> com.util.tag.html.TextTag</tagclass >  //對應的java文件路徑
             <bodycontent> empty</bodycontent >

             <attribute>
                   <name> property</name >
                   <required> false</required >
                   <rtexprvalue> true</rtexprvalue >
             </attribute>
       </tag>
</taglib>

2.java類繼承:BodyTagSupport類, 覆寫方法:doTagStart()
public class LabelTag extends BodyTagSupport {
private String property = null;
@Override
public int doStartTag() throws JspException {
            //doSomething...
            
            this.pageContext.getOut().write(...........輸出本身的內容............);
            return super.doStartTag();
        }

        //setter跟getter方法,用於獲取該屬性的值
}


3.jsp頁面引用:
<%@ taglib prefix=" yao" uri=" http://com.yao/tags/html" %>
< yao: TextTag property= "text/name" />
-----------------------------------------------------------------------------------------------------------------------------------
運行的順序是:servlet->jsp->labelTag.java
針對request,map,javabean實現 (對象/屬性) 值的輸出:
java代碼:
public class LabelTag extends BodyTagSupport {
	private String property = null;
	
	@SuppressWarnings("unchecked")
	@Override
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest)this.pageContext.getRequest();
		String[] str = property.split("/");
		Object targetObject = request.getAttribute(str[0]);
		Object targetValue = null ;

		try {
			if(targetObject instanceof String){
				targetValue = targetObject;
			}else if(targetObject instanceof Map){
				targetValue = ((Map)targetObject).get(str[1]);
			}else{
				targetValue = labelForJavaBean(targetObject,str[1]);
			}
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		try {
			this.pageContext.getOut().write(targetValue.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.doStartTag();
	}
	
	/**
	 * 針對普通javabean對象的值的輸出
	 * @author yao
	 * @param targetObject
	 * @param propertyName
	 * @return * @throws ClassNotFoundException
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	@SuppressWarnings("unchecked")
	public Object labelForJavaBean(Object targetObject,String propertyName) throws ClassNotFoundException,
				NoSuchMethodException,InvocationTargetException,IllegalAccessException{
		StringBuffer sb = new StringBuffer();
		Class clazz = Class.forName(targetObject.getClass().getName());
		sb.append("get").append(upperFirstWord(propertyName));
		Method method = clazz.getDeclaredMethod(sb.toString());
		return method.invoke(targetObject);
	}
	
	
	
	public String upperFirstWord(String str){
		String firstWord = str.substring(0,1);
		return str.replaceFirst(firstWord, firstWord.toUpperCase());
	}
	
	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}
}
Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Text text = new Text();
	  	text.setName("yaolihua");
	  	text.setSex("man");
	  	
	  	
	  	Map map = new HashMap();
	  	map.put("year","2012");
	  	map.put("month","08");
	  	map.put("day","01");
	  	
	  	
	  	request.setAttribute("text", text);
	  	request.setAttribute("test","text");
	  	request.setAttribute("map", map);
	  	request.getRequestDispatcher("/index.jsp").forward(request, response);
	}
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  
 web-jsptaglibrary_2_0.xsd" verson="2.0">  
 
	<tlib-version>1.0</tlib-version>
	<jspversion>1.1</jspversion>
	<shortname>yao</shortname>
	<uri>http://com.yao/tags/html</uri>
	
	<tag>
		<name>label</name>
		<tagclass>com.util.tag.html.LabelTag</tagclass>
		<bodycontent>empty</bodycontent>

		<attribute>
			<name>property</name>
			<required>false</required>
			<rtexprvalue>true</rtexprvalue> 
		</attribute>
	</tag>
 
</taglib>
jsp文件:
<%@ taglib prefix="yao" uri="http://com.yao/tags/html" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>page</title>
  </head>
  
  <body>
    <yao:label property="map/year" />
    <yao:label property="text/name" />
    <yao:label property="text/sex"/>
    <yao:label property="test" />
  </body>
</html>
相關文章
相關標籤/搜索