1

我正在编写一个 JSP 页面,它从 servlet 检索变量并将它们输出给用户,我当前的代码工作如下:

String uploadStatus = (String) request.getAttribute("uploadStatus");
String readStatus = (String) request.getAttribute("readStatus");
String saveStatus = (String) request.getAttribute("saveStatus");
String completeStatus = (String) request.getAttribute("completeStatus");
String applicationName = (String) request.getAttribute("applicationName"); 
String buildAndroid = (String) request.getAttribute("buildAndroid"); 
String buildWindows = (String) request.getAttribute("buildWindows"); 
String buildiOS = (String) request.getAttribute("buildiOS");
String uploadCompleteStatus = (String) request.getAttribute("uploadCompleteStatus"); 
String startBuild = (String) request.getAttribute("startBuild"); 
String finishBuild = (String) request.getAttribute("finishBuild"); 

out.println(uploadStatus + "<br>");
out.println(readStatus + "<br>");
out.println(saveStatus + "<br>");
out.println(applicationName + "<br>");
out.println(buildAndroid + "<br>");
out.println(buildWindows + "<br>");
out.println(buildiOS + "<br>");
out.println(uploadCompleteStatus + "<br>");
out.println(startBuild + "<br>");
out.println(finishBuild + "<br>");

它工作得很好,但代码很长而且不是很可扩展。我想知道他们是否是一种在 JSP 中使用 for 循环和可能的通配符更简单的方法。有人有什么想法吗?

谢谢

4

3 回答 3

4

为什么不将所有状态变量添加到 aList<String>并添加Listrequest属性?这样,您可以使用单个循环来输出所有变量。

List<String> statusItems = new ArrayList<>();
statusItems.add(uploadStatus);
statusItems.add(readStatus);
...
request.setAttribute("statusItems", statusItems);

顺便说一句,不鼓励在 JSP 中使用 scriptlet。使用JSTL

<c:forEach var="status" items="${requestScope.statusItems}">
  ${status} <br/>
</c:forEach>

或者如果您希望您的状态值被 HTML 转义,请使用 inside <c:out value="${status}"/>forEach

于 2013-08-08T10:23:41.703 回答
3

使用 req.getAttributeNames()

    Enumeration attrs =  req.getAttributeNames();
    while(attrs.hasMoreElements()) {
        String val = (String) req.getAttribute((String) attrs.nextElement());
        System.out.println(val);
    }
于 2013-08-08T10:25:14.367 回答
1

当然试试这个:

for (String lAttributeName : request.getAttributeNames()){
       System.out.println((String)request.getAttribute(lAttributeName));
}
于 2013-08-08T10:25:09.497 回答