Tuesday, April 5, 2011

How do I dynamically access request parameters with JSP EL?

I'm looping through a list of items, and I'd like to get a request parameter based on the item's index. I could easily do it with a scriptlet as done below, but I'd like to use expression language.

<c:forEach var="item" items="${list}" varStatus="count">

   <!-- This would work -->
   <%=request.getParameter("item_" + count.index)%>

   <!-- I'd like to make this work -->
   ${param.?????}

</c:forEach>
From stackoverflow
  • <c:set var="index" value="item_${count.index}" />
    ${param[index]}
    

    Unfortunately, + doesn't work for strings like in plain Java, so

    ${param["index_" + count.index]}
    

    doesn't work ;-(

    ScArcher2 : i corrected the reference to params. it's supposed to be param. But your answer gave me what I needed to get it working. Thanks!
  • There is a list of implicit objects in the Expression Language documentation section of the J2EE 1.4 documentation. You're looking for param.

    ScArcher2 : Thanks I looked it up and realized I was accessing the wrong thing. The main thing I was missing was the bracket syntax for accessing a property.
  • You just need to use the "square brackets" notation. With the use of a JSTL <c:set> tag you can generate the correct parameter name:

    <c:forEach var="item" items="${list}" varStatus="count">
      <c:set var="paramName">item_${count.index}</c:set>
      ${param[paramName]}
    </c:forEach>
    

0 comments:

Post a Comment