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

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

这次要实现的是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;

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航