当前位置: 移动技术网 > IT编程>开发语言>Jsp > JSP标签自定义(2)---getProperty

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

2019年04月19日  | 移动技术网IT编程  | 我要评论

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

/**
* 类说明:标签处理类,仿(sun企业级应用的首选)的getproperty标签
* 创建日期:2004-7-2
* 修改日期:2004-7-2
* 创建人: dever
*/

package cn.dever.tag;
import javax.servlet.jsp(sun企业级应用的首选).*;
import javax.servlet.jsp(sun企业级应用的首选).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 jsp(sun企业级应用的首选)tagexception 
 {
   
  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(illegalaccess(小型网站之最爱)exception e){
   system.out.print("illegal access(小型网站之最爱) error!");
  }
  catch(nosuchmethodexception e){
   throw new jsp(sun企业级应用的首选)tagexception(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 jsp(sun企业级应用的首选)tagexception
    {
     try{
   jsp(sun企业级应用的首选)writer out = pagecontext.getout(); //输出得到的结果
   out.println(result);
     }
  catch(java.io.ioexception e){
   system.out.println("io error !");
  }
  
        return eval_page; 
    }
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网