我正在尝试记录HttpServletRequest属性集合的内容。我需要在servlet首次启动时执行此操作,并在servlet完成之前再次执行此操作。我这样做是为了了解一个狡猾且维护不良的servlet。因为我需要尽可能少的影响,所以不能选择servlet过滤器。
所以这就是问题所在。当servlet启动时,我将遍历HttpServletRequest.getAttributeNames()返回的枚举。但是,当我想再次遍历它时,getAttributeNames()。hasMoreElements()返回“false”!我找不到任何“重置”枚举的方法。更糟糕的是,即使我使用HttpServletRequest.setAttribute()向集合添加属性,当我调用getAttributeNames()时,仍会得到“false”的结果.hasMoreElements()。
这真的有可能吗?是否真的无法多次遍历属性名称?
根据要求,这是我的代码。这很简单 - 不要以为我在做任何有趣的事情。
/**
*
* 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 + "}";
}
}
答案 0 :(得分:18)
也许你应该在你调用HttpServletRequest.setAttribute()
的地方发布代码。
在这一点上,似乎你的狡猾和维护不良的servlet正在删除你对getAttributeNames()
的两次调用之间的属性,但是没有任何代码示例,很难说。
<强>更新强>
你的代码中没有任何内容因为错误而跳出来......所以我在handleRequest()
内制作了一个非常简单的测试用例并给它一个旋转(使用jboss-eap-4.3作为我的容器)。我必须首先手动设置一个属性,因为我对请求属性的理解是它们总是设置在服务器端(即如果我没有设置它,那么我没有获得任何输出Enumeration
返回getAttributeNames()
1}}是空的。
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());
}
输出
INFO [STDOUT] muckingwattrs
INFO [STDOUT] ----------------------------
INFO [STDOUT] muckingwattrs
所以也许你的容器没有正确实现getAttributeNames()
?也许直接在handleRequest()
或doGet()/doPost()
中尝试一个非常简单的测试用例。