有没有办法不止一次迭代HttpServletRequest.getAttributeNames()?

san*_*oid 6 java attributes enumeration servlets enumerator

我正在尝试记录HttpServletRequest属性集合的内容.我需要在servlet首次启动时执行此操作,并在servlet完成之前再次执行此操作.我这样做是为了了解一个狡猾且维护不良的servlet.因为我需要尽可能少的影响,servlet过滤器不是一个选项.

所以这就是问题所在.当servlet启动时,我将遍历HttpServletRequest.getAttributeNames()返回的枚举.但是,当我想再次遍历它时,getAttributeNames().hasMoreElements()返回"false"!我找不到任何"重置"枚举的方法.更糟糕的是,即使我使用HttpServletRequest.setAttribute()向集合添加属性,当我调用getAttributeNames().hasMoreElements()时,我仍然得到"false"的结果.

这真的有可能吗?难道真的没有办法不止一次遍历属性名称吗?

根据要求,这是我的代码.这很简单 - 不要以为我做任何有趣的事情.

/**
 * 
 * Returns the contents of the Attributes collection, formatted for the InterfaceTracker loglines
 * 
 */
@SuppressWarnings("unchecked")
public static String getAttributes(HttpServletRequest request) {
    try {       
        StringBuilder toLog = new StringBuilder();  

        Enumeration attributeNames = request.getAttributeNames();           

        while(attributeNames.hasMoreElements()) {
            String current = (String) attributeNames.nextElement();

            toLog.append(current + "=" + request.getAttribute(current));            

            if(attributeNames.hasMoreElements()) {
                toLog.append(", ");
            }           
        }       

        return "TRACKER_ATTRIBUTES={"+ toLog.toString() + "}";
    }
    catch (Exception ex) {
        return "TRACKER_ATTRIBUTES={" + InterfaceTrackerValues.DATA_UNKNOWN_EXCEPTION_THROWN + "}";
    }               
}
Run Code Online (Sandbox Code Playgroud)

new*_*all 18

也许您应该在您调用的地方发布代码HttpServletRequest.setAttribute().

在这一点上,似乎你的狡猾和维护不良的servlet正在删除你的两个调用之间的属性getAttributeNames(),但没有任何代码示例,很难说.

UPDATE

你的代码中没有任何内容因为错误而跳出来......所以我在里面制作了一个非常简单的测试用例handleRequest()并给它一个旋转(使用jboss-eap-4.3作为我的容器).我必须首先手动设置一个属性,因为我对请求属性的理解是它们总是设置在服务器端(即如果我没有设置它,那么我没有得到任何输出,因为Enumeration返回的getAttributeNames()是空的).

request.setAttribute("muckingwattrs", "Strange");

Enumeration attrs =  request.getAttributeNames();
while(attrs.hasMoreElements()) {
    System.out.println(attrs.nextElement());
}

System.out.println("----------------------------");

Enumeration attrs2 =  request.getAttributeNames();
while(attrs2.hasMoreElements()) {
    System.out.println(attrs2.nextElement());
}
Run Code Online (Sandbox Code Playgroud)

产量

INFO  [STDOUT] muckingwattrs
INFO  [STDOUT] ----------------------------
INFO  [STDOUT] muckingwattrs
Run Code Online (Sandbox Code Playgroud)

那么也许你的容器没有getAttributeNames()正确实现?也许直接在handleRequest()或尝试一个非常简单的测试用例doGet()/doPost().