简体   繁体   English

JSTL适用于循环语法

[英]JSTL proper for loop syntax

I'm pretty new to JSTL and well Java in general. 我对JSTL和Java一般都是新手。 Is there a better way to format this for loop, it seems like I could break it up a little more to make it cleaner. 是否有更好的方法来格式化这个for循环,似乎我可以将它分解一点以使其更清洁。 Ideally I'd like to not have to escape the strings but not sure how or if there is a better way? 理想情况下,我不想逃避字符串,但不确定如何或是否有更好的方法? I know when declaring variables in JSTL you can do something like below with the property inside the c: tag. 我知道在JSTL中声明变量时,您可以使用c:标记内的属性执行类似下面的操作。 Is there something similar you can do with for loops? 你可以用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>

Any help is greatly appreciated! 任何帮助是极大的赞赏!

Your JSP has a lot of java code (scriptlets) on it. 你的JSP上有很多java代码(scriptlets)。 Using JSTL can help you get away from using scriptlets, and therefore helps you separate code logic from your presentation which is better for maintainability. 使用JSTL可以帮助您摆脱使用scriptlet,因此可以帮助您将代码逻辑与演示文稿分开,这样可以提高可维护性。 As you can see, you have a good bit of straight java code on your page. 如您所见,您的页面上有一些简单的java代码。

This is how I've used JSTL for loops. 这就是我如何使用JSTL for循环。 Typically on the server side, I'll set exactly what I need in a request attribute. 通常在服务器端,我将在请求属性中准确设置我需要的内容。 So this may depend on your tool/framework, but generally you can somehow access an HttpServletRequest. 所以这可能取决于你的工具/框架,但通常你可以以某种方式访问​​HttpServletRequest。 Just using the HttpServlet's doGet() method as an example 仅使用HttpServlet的doGet()方法作为示例

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

Then on the JSP, I'll just loop through whatever I set 然后在JSP上,我将循环遍历我设置的任何内容

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM