The getProperty tag is implemented this time. The main knowledge point is how to use reflection to call methods in the instance. Important parts have been annotated.
/**
* Class description: Tag processing class, similar to the getProperty tag of jsp (preferred for SUN Enterprise applications)
* Creation date: 2004-7-2
* Modification date: 2004-7-2
* Created by: dever
*/
Package cn. dever. tag;
Import javax. servlet. jsp (preferred for SUN Enterprise Applications ).*;
Import javax. servlet. jsp (preferred for SUN Enterprise Applications). tagext .*;
Import java. lang. reflect .*;
Public class GetProperty extends TagSupport
{
Private String name; // obtain the class name.
Private String property; // attribute name
Private String method; // method Name of the returned property
Private String result; // The final output result.
Public void setName (String s ){
This. name = s;
}
Public String getName () {return this. name ;}
Public void setProperty (String property)
{
This. property = property; // convert the property name to the method name for obtaining the 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 (preferred for SUN Enterprise Applications) TagException
{
Try {
Object getInstance = pageContext. getAttribute (name); // get the instance of the class
Class insClass = getInstance. getClass ();
Class [] typeParameter = new Class [] {}; // defines an array of parameter types of methods
Method methInstance = insClass. getMethod (method, typeParameter); // obtain a Method instance based on the method name.
Object [] objParameter = new Object [] {}; // parameter array of the called Method
Result = methInstance. invoke (getInstance, objParameter). toString (); // call the method in the class instance to obtain the serialized string.
}
Catch (Illegalaccess (a favorite of small websites) Exception e ){
System. out. print ("Illegal access (a favorite of small websites) Error! ");
}
Catch (NoSuchMethodException e ){
Throw new jsp (preferred for SUN Enterprise Applications) 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 (preferred for SUN Enterprise Applications) TagException
{
Try {
Jsp (preferred for SUN Enterprise Applications) Writer out = pageContext. getOut (); // output result
Out. println (result );
}
Catch (java. io. IOException e ){
System. out. println ("IO Error! ");
}
Return EVAL_PAGE;
}
}