自定义Tag文件封装步骤与示例

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

相同的颜色就是对应的名称。

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

 
 
 
        1.0
        1.1
        yao
        http://com.yao/tags/html
      
       
              TextTag
              com.util.tag.html.TextTag  //对应的java文件路径
              empty

             
                    property
                    false
                    true
             
       

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文件:
  
  
 
	1.0
	1.1
	yao
	http://com.yao/tags/html
	
	
		label
		com.util.tag.html.LabelTag
		empty

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



  
    page
  
  
  
    
    
    
    
  






转载于:https://my.oschina.net/u/185335/blog/70281

你可能感兴趣的:(自定义Tag文件封装步骤与示例)