Search code examples
javacatalina

How do I properly print enumerator elements?


I am trying to understand java program written by someone else and I do not know java. I have written a short method fro dumping attributes of request object.

public void dumpRequest(HttpServletRequest request) {

    String[] attrNames = new String[100]; // hard coded
    int ani = 0;

    Enumeration rns = request.getAttributeNames();
    while (rns.hasMoreElements()) {
        out.println("attribute name: " + rns.nextElement());
        attrNames[ani] = rns.nextElement().toString();
        ani = ani + 1;
    }

    out.println("" + ani + " atributes");
    String cn;
    for (int n = 0; n < ani; n++) {
        cn = attrNames[n];
        out.println("** " + cn + " - " + request.getAttribute(cn));
    }
    out.println("++++++++++++++++++++++");

}

To my horror, I have realised that NetBeans variables tab shows twice more attributes on the request object compared to my code output. The enumeration seems to be documented here: https://tomcat.apache.org/tomcat-4.1-doc/catalina/docs/api/org/apache/catalina/util/Enumerator.html

What am I doing wrong?


Solution

  • You call nextElement method twice in this block:

    while (rns.hasMoreElements()) {
            out.println("attribute name: " + rns.nextElement());
            attrNames[ani] = rns.nextElement().toString();
            ani = ani + 1;
        }
    

    you should call nextElement once. Put it in variable and then use that variable.