您现在的位置:计算机技术学习网 > 技术中心 > WEB编程 > JSP >

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

来源:网络 责任编辑:栏目编辑 发表时间:2013-07-01 12:59 点击:

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

/**
* 类说明:标签处理类,仿jsp(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; 
    }
}

    相关新闻>>

      发表评论
      请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
      用户名: 验证码:点击我更换图片
      最新评论 更多>>

      推荐热点

      • JSP与Servlet
      • 自己动手写MiniBBS系列(基本篇)之用户登录
      • JSP取当前日期
      • JDBC 入门(一)
      • 打开一个jsp页面默认查询所有数据,调用action
      • 使用JSP标签库验证用户的输入(2)完
      • WIN98/2000下的jsp服务器
      • 自定义JSP标签(tag)浅议
      • Struts学习傻瓜式入门篇
      网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
      Copyright © 2008-2015 计算机技术学习交流网. 版权所有

      豫ICP备11007008号-1