编程教程
你的位置: 中国个人站长站 -- 网络编程 -- JSP教程 -- 教程正文 JSP标签自定义(2)---getProperty
推荐位

JSP标签自定义(2)---getProperty

中国个人站长站 JSP教程 点击数: 更新时间:2004-8-25

这次要实现的是getProperty标签。主要知识点是怎么用反射去调用实例中的方法。重要部分已用注释标注。

/** * 类说明:标签处理类,仿JSP的getProperty标签* 创建日期:2004-7-2* 修改日期:2004-7-2* 创建人: dever */

package cn.dever.tag;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;import java.lang.reflect.*;

public class GetProperty extends TagSupport{ private String name;  //得到类名称 private String property; //得以属性名 private String method; //返回属性的方法名 private String result; //最终输出结果  public void setName(String s) {     this.name = s;   }  public String getName(){return this.name;}   public void setProperty(String property) {  this.property = property;//将属性名转换成获得属性的方法名  int length = property.length();  String temp=property.substring(0,1).toUpperCase()+property.substring(1,length);  this.method="get"+temp; } public String getProperty(){return this.property;}

 public int doStartTag() throws JspTagException   {     try{      Object getInstance=pageContext.getAttribute(name); //得到类的实例   Class insClass = getInstance.getClass();       Class[] typeParameter = new Class[]{}; //定义方法的参数类型数组   Method methInstance = insClass.getMethod(method,typeParameter); //根据方法名称得到一个方法实例   Object[] objParameter = new Object[]{}; //被调用方法的参数数组   result = methInstance.invoke(getInstance,objParameter).toString(); //在类实例中调用方法,得到串行化后的字符串     }  catch(IllegalAccessException e){   System.out.print("Illegal Access Error!");  }  catch(NoSuchMethodException e){   throw new JspTagException(method+"() is not exist!");  }  catch(InvocationTargetException e){   System.out.print("Invocation Target Error!");  }  catch(NullPointerException e){   result="null";  }       return EVAL_BODY_INCLUDE;  }        public int doEndTag() throws JspTagException     {     try{   JspWriter out = pageContext.getOut(); //输出得到的结果   out.println(result);     }  catch(java.io.IOException e){   System.out.println("IO Error !");  }          return EVAL_PAGE;      }}

教程录入:swh    责任编辑:swh 
个人站长站与你风雨同舟!
本站所提供的资源均来源于互联网,如有侵权行为,请与本站管理员联系,我们会第一时间删除!
·如果您发现《JSP标签自定义(2)---getProperty》文章有错误,也请通知我们修改!
联系邮箱chinageren#126.com,谢谢支持!
站内搜索:
版权所有:中国个人站长站 2007-2008 未经授权禁止复制或建立镜像 客服QQ号:112731235
copyright © 2007-2008 www.ChinaGeRen.com online services. all rights reserved. 苏ICP备05000059号