Results 1 to 2 of 2
  1. #1
    RollzHard is offline Member
    Join Date
    Mar 2011
    Rep Power

    Default EL & <c:forEach>

    Wondering how I can get this done.

    I have a class ShoppingCartItem which has a variable called 'Object item' and inside of the ShoppingCart I have a hashmap of ShoppingCartItems called items.

    inside my servlet I setup a session attribute called cart which is a shopping cart.

    inside my jsp I am trying to do this

    <c:forEach var="item" items="${cart.items}">
    ${item.quantity} // works fine
    ${item.bookId} // fails
    ${item.title} // fails...

    How can I cast the item to a book?

  2. #2
    KyJavaGuy is offline Member
    Join Date
    Mar 2011
    Rep Power

    Default Shopping cart items

    Your question is a little unclear. My understanding of your explanation that you have a class called ShoppingCartItem that has in it an instance of Object called item. You are iterating through a list of ShoppingCartItems in your jsp and identifying each instance of ShoppingCartItem as "item". One big guess I have made here is that quantity belongs to the ShoppingCartItem whereas bookId and title belong to the item object instance within ShoppingCartItem.

    So it occurs to me that you need to refer to an instance of the Object named "item" within an instance of ShoppingCartItem, which you have called item in your iteration, as
    Java Code:
    You have inadvertantly made the code more difficult to understand with your choice of names in your jsp and class. Maybe a better choice would be to call your Book instance in ShoppingCartITem something other than item or change your choice of names in your jsp to make it a bit clearer.

    I don't think you need to worry about casting item as Book. However, I will ask why you can't cast item as Book in the first place?

Similar Threads

  1. x:forEach problem
    By GrahamButcher in forum XML
    Replies: 0
    Last Post: 10-22-2010, 03:42 PM
  2. <c:forEach to list data in X columns
    By polygrimm in forum JavaServer Pages (JSP) and JSTL
    Replies: 0
    Last Post: 12-04-2009, 09:27 PM
  3. JSTL forEach Query
    By wonderpets in forum JavaServer Pages (JSP) and JSTL
    Replies: 5
    Last Post: 07-14-2008, 06:35 PM
  4. How to use Foreach on an Array
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-16-2008, 11:06 PM
  5. Question regarding foreach loop...
    By theonlywalks in forum New To Java
    Replies: 2
    Last Post: 03-15-2008, 07:15 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts