简体   繁体   中英

JSTL proper for loop syntax

I'm pretty new to JSTL and well Java in general. 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. 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. Is there something similar you can do with for loops?

<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. 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. As you can see, you have a good bit of straight java code on your page.

This is how I've used JSTL for loops. 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. Just using the HttpServlet's doGet() method as an example

// 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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