JSTL适用于循环语法

时间:2013-04-19 01:40:32

标签: java performance jstl

我对JSTL和Java一般都很陌生。是否有更好的方法来格式化这个for循环,似乎我可以将它分解一点以使其更清洁。理想情况下,我不想逃避字符串,但不确定如何或是否有更好的方法?我知道在JSTL中声明变量时,您可以使用c:标记内的属性执行类似下面的操作。你可以用for循环做类似的东西吗?

<c:set var="childNode"><%= properties.get("childrenNode", "") %></c:set>

<c:forEach items="<%=childResults.getPath((Child)pageContext.getAttribute(\"childPage\"), currentPage, new showChildrenFilter())%>" var="segment" varStatus="status">
   ${displaySomething}
</c:forEach>

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

你的JSP上有很多java代码(scriptlet)。使用JSTL可以帮助您摆脱使用scriptlet,因此可以帮助您将代码逻辑与演示文稿分开,这样可以提高可维护性。如您所见,您的页面上有一些简单的java代码。

这就是我使用JSTL for循环的方式。通常在服务器端,我将在请求属性中准确设置我需要的内容。所以这可能取决于你的工具/框架,但通常你可以以某种方式访问​​HttpServletRequest。仅使用HttpServlet的doGet()方法作为示例

// this is in my servlet
public void doGet(HttpServletRequest req, HttpServletResponse resp) 
{
   Collection<Circle> circles = // some logic here 
   req.setAttribute("circles", circles);
}

然后在JSP上,我将循环遍历我设置的任何内容

<c:forEach items="${circles}" var="circle">
   Radius: ${circle.radius}, Color: ${circle.color} <br/>
</c:forEach>