1

I am new to using JSP and i'm trying to do something like:

<% for (int i=0; i<numTables; i++) { %>
<h3> person <%=i%></h3>
<% } %>

numTables is a variable in the HomeController class.
I've also executed in the controller:

 model.addAttribute("numTables", numTables);

and if I write:

<h1>${numTables}</h1>

It prints the correct value. But I couldn't find a way to put this value as the value of numTables in the for loop.
please help. thanks.

Edit: It has to be done with scriptlets.

tomermes
  • 22,950
  • 16
  • 43
  • 67

2 Answers2

3

You are better off avoiding scriptlets. JSTL tags can perform the same function e.g.

<c:forEach var="i" begin="0" end="${numTables}" >
    <h3>person ${i}</h3>
</c:forEach>
krock
  • 28,904
  • 13
  • 79
  • 85
3

It's stored as a request attribute:

Integer numtables = (Integer) request.getAttribute("numTables");

Or whenever you're unsure in which scope it is:

Integer numtables = (Integer) pageContext.findAttribute("numTables");

However, you're going the wrong path by avoiding taglibs like JSTL. Scriptlets are discouraged since JSP 2.0 which was released almost a decade(!) ago. If I were your CS tutor, you'd get negatives for this.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • In which part of the specification in JSP 2.x does it say scriptlets are discouraged? – Raul Lapeira Herrero Mar 12 '20 at 18:59
  • @RaulLapeiraHerrero: click the "discouraged" link in answer. For an related Q&A see also https://stackoverflow.com/q/3177733 – BalusC Mar 12 '20 at 19:21
  • The fact that JSTL proposes not using java in JSPs does not mean the JSP 2.x discourages it... in the spec there is no mention to such a thing. – Raul Lapeira Herrero Mar 13 '20 at 11:20
  • Click the link in my previous comment for relevant quotes which you apparently missed from the coding conventions document. – BalusC Mar 13 '20 at 15:15
  • I missed nothing. I am informing you a convention document is not the specification discouraging anything, but thanks for pointing out a 10 year old specification is old. – Raul Lapeira Herrero Mar 14 '20 at 17:40