View RSS Feed

My Java Tips

Using reflection QueryRequestTag

Rate this Entry
by , 05-21-2011 at 09:51 PM (1148 Views)
This post presents an example that show use of reflection in creating a tag. The created tag will call some methods of the request (HttpServletRequest) object using reflection.

Source code for the QueryRequestTag handler is presented below:

Java Code:
public class QueryRequestTag extends ExTagSupport {
    static Object []params = new Object[0];
    
    static Hashtable methods = new Hashtable();
    
    static LocalStrings ls =
    LocalStrings.getLocalStrings(QueryRequestTag.class);
    
    static {
        try {
            Class []p = new Class[0];
            
            Class reqc = HttpServletRequest.class;
            
            methods.put("method",
            reqc.getMethod("getMethod", p));
            
            methods.put("queryString",
            reqc.getMethod("getQueryString", p));
            
            methods.put("requestURI",
            reqc.getMethod("getRequestURI", p));
            
            methods.put("userPrincipal",
            reqc.getMethod("getUserPrincipal", p));
            
            methods.put("remoteUser",
            reqc.getMethod("getRemoteUser", p));
            
            } catch(Throwable t) {
        }
    }
    protected String property = null;
    
    public void setProperty(String property)
    {
        this.property = property;
        
    }
    public int doStartTag()
    throws JspException
    {
        try {
            Method m = (Method)methods.get(property);
            
            if(null != m) {
                writeHtml(pageContext.getOut(),
                m.invoke(pageContext.getRequest(),
                params).toString());
                
                return SKIP_BODY;
                
                } else {
            }
            } catch(java.io.IOException ioe) {
            } catch(InvocationTargetException ite) {
            } catch(IllegalAccessException iae) {
        }
    }
    protected void clearProperties()
    {
        property = null;
        
        super.clearProperties();
        
    }
}
Note: exception handling is not done in proper way. Proper logging should be done to make things work in better way.

Now lets talk about the code. We obtain method objects from the HttpServletRequest class and stores them in a method cache for later use.
An empty array of classes and procure an instance of HttpServletRequest from which to retrieve the methods.

The discussed tag extracts method objects from the HttpServletRequest class and stores them in a hashtable. The key to the stored methods is the name of the property the method retrieves.

Submit "Using reflection QueryRequestTag" to Facebook Submit "Using reflection QueryRequestTag" to Digg Submit "Using reflection QueryRequestTag" to del.icio.us Submit "Using reflection QueryRequestTag" to StumbleUpon Submit "Using reflection QueryRequestTag" to Google

Comments