Question

i want foreach items add arrays list

<sql:query var="query"  dataSource="${db}">

   select fname, lname from users where fname='ali'

</sql:query>

<c:forEach items="${query.rows}" var="result"> 

 <% 

  ArrayList l= new ArrayList();
  l.add("${result.fname}");
  l.add("${result.lname}");


 for(int i=0; i<l.size(); i++)
   {
   out.println(l.get(i));
   }
 %>

</c:forEach>

output result:

${result.fname} ${result.lname}  ${result.fname} ${result.lname}  ${result.fname} ${result.lname} 

what is wrong ?

Was it helpful?

Solution

You can't use jstl inside scriptlet..

Save the value of ${result.fname} using <c:set> in page scope. And use the variable inside the scriptlet.

e.g.

<c:forEach items="${query.rows}" var="result">
     <c:set var="lname" value="${result.lname}"  />
     <c:set var="fname" value="${result.fname}" />

     <%
         ArrayList l= new ArrayList();

         l.add((String)pageContext.getAttribute("fname"));
         l.add((String)pageContext.getAttribute("lname"));

         for(int i=0; i<l.size(); i++)
         {
             out.println(l.get(i));
         }
     %>


</c:forEach>

For more information, http://docs.oracle.com/javaee/1.4/tutorial/doc/JSTL4.html

http://javapapers.com/jsp/jsp-life-cycle-explain/

http://docs.oracle.com/cd/E13222_01/wls/docs81/taglib/handler.html

UPDATE

EL attributes are stored in the scope - page, request, session, application The <c:set> tag example doesn't specify a scope, so therefore you could get it like this:

 <c:set var="fname" value="${result.fname}" />

  <%
       String fname = (String)pageContext.getAttribute("fname"); 
       System.out.println(fname);
  %>

alternatively exploit the feature of the useBean tag that creates a scriptlet variable:

<c:set var="fname" value="${result.fname}" />
<jsp:useBean id="fname" type="java.lang.String"/>
<%
  System.out.println(fname);
 %>

Note that the EL variable and the Scriptlet variable are initially pointing at the same String. But changing the string in scriptlet code will change the value it is pointing at, while leaving the EL variable untouched.

OTHER TIPS

As you are adding ${result.fname} using quotes. JVM considers it as string literals. So you are getting result like this.

use foreach loop in jstl for eg check out the eg here!

and avoid java code in jsp page check out this link

How to avoid Java code in JSP files?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top