View RSS Feed

My Java Tips

Using reflection QueryRequestTag

Rate this Entry
by , 05-21-2011 at 09:51 PM (1656 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 =
    static {
        try {
            Class []p = new Class[0];
            Class reqc = HttpServletRequest.class;
            reqc.getMethod("getMethod", p));
            reqc.getMethod("getQueryString", p));
            reqc.getMethod("getRequestURI", p));
            reqc.getMethod("getUserPrincipal", p));
            reqc.getMethod("getRemoteUser", p));
            } catch(Throwable t) {
    protected String property = null;
    public void setProperty(String property)
    { = property;
    public int doStartTag()
    throws JspException
        try {
            Method m = (Method)methods.get(property);
            if(null != m) {
                return SKIP_BODY;
                } else {
            } catch( ioe) {
            } catch(InvocationTargetException ite) {
            } catch(IllegalAccessException iae) {
    protected void clearProperties()
        property = null;
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 Submit "Using reflection QueryRequestTag" to StumbleUpon Submit "Using reflection QueryRequestTag" to Google