Search code examples
javajspelscriptlet

using EL inside java tag


I have an attribute which I have forwarded from a servelet to a jsp file and while I can use this object with EL I'd like to know how to access it inside the java tags. An example is something like the following:

 Searching for "${search_phrase}" returned
  <c:forEach var="video" items="${results}">
      ${video.getVideoName()}
      ${video.getVideoID()}       
  </c:forEach>

So results here is an ArrayList of type Video which is forwarded from a servlet to a jsp

I would like to access this ArrayList inside <% %> tags in order to perform some more involved tasks that I cant do with EL.

Anybody know how to do this?

On a side note, this ArrayList I'm creating could potentially get large. Where is this stored? On the server or in some users temp files? If it's stored in server memory does it get cleaned after some period of time / an event such as the user that requested the ArrayList closes connection to server?


Solution

  • It all depends where you stored the list. If you stored it in a request attribute (and not anywhere else), then it will be eligible to garbage-collection when the request has been handled.

    If you stored it in a session attribute, then it will be stored in the server memory (and/or the file system or the database depending on the container configuration) until the session times out or is invalidated, or until you remove it. HTTP is a stateless protocol. The user doesn't have a connection to the server.

    Java code between <% %> is not a java tag. It's scriptlet, and should not be used in a JSP. If you need to do something that EL or JSP tags can't do easily, then either

    • write a custom JSP tag yourself, put the Java code in this JSP tag, and invoke the tag from the JSP, or
    • or write a custom EL function, and invoke this function from the JSP
    • or prepare the work in a controller (servlet, MVC framework action) before dispatching to the JSP, so that the JSP can generate the markup easily.

    The list is accessible using the getAttribute method corresponding to the setAttribute method you used to store the list:

    HttpServletRequest.setAttribute() --> HttpServletRequest.getAttribute()
    HttpSession.setAttribute() --> HttpSession.getAttribute()
    ServletContext.setAttribute() --> ServletContext.getAttribute()