站内搜索: 请输入搜索关键词

当前页面: 开发资料首页JSP 专题JSP标签自定义(2)---getProperty

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

摘要: JSP标签自定义(2)---getProperty

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



↑返回目录
前一篇: Struts,MVC 的一种开放源码实现用这种servlet和JSP框架管理复杂的大型网站
后一篇: JSP标签自定义(3)---setProperty