4

This might be a very newbie question, but I didn't find anything satisfying

I want to do somethign like this in JSP (out of the box preferably):

e.g. in a file called products.jsp an imaginary implementation that explains what I want

<x:named-segment name="product">
     Product: <strong>${product.name}</strong> <br/>
     price: ${product.price}
</x:named-segment>

and later on use this in various location in the same JSP it is defined

<table>
   <c:forEach var="product" items="${products}">
      <tr>
         <td><x:use-segment name="product"/></td>
      </tr>
   </c:forEach>
</table>

I've looked into JSP tags, and JSP Fragements, but there the fragment snippet is just passed from the caller JSP to the JSP tag, and I want it to be in the same location

Is the only solution is to craete a JSP tag for that specific small snippet (or include?)

Am I missing something very basic?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Eran Medan
  • 44,555
  • 61
  • 184
  • 276
  • "but there the fragment snippet is just passed from the caller JSP to the JSP tag, and I want it to be in the same location" - I didn't get that one.. – Bozho Feb 08 '10 at 12:06
  • 1
    He want to define the template in the very same JSP page. Think as realworld example about `xsl:template` which can be placed in the same XSL file as where it's been used. Maybe Tiles or Sitemesh can do. I don't know, never used them as well. – BalusC Feb 08 '10 at 12:27
  • @Bozho - the idea of fragments is that the jsp tag can define just the layout, and the fragment is a "callback" or "user draw" snippet of JSP (wituot scriptlets by the way) that can be plugged in the tag, this is nice, but not what I want... @BalusC - Yep, and Yep – Eran Medan Feb 08 '10 at 14:08

2 Answers2

1

If the small piece of text that you want at many places is static, I would recommend a JSP include. However, if the text is from database/Flat file/XML, I would recommend using a custom tag. From the example you've provided, it appears as though you are trying to list products and their price. This can be easily accomplished in a custom tag.

In your tag class, read the data, create a method that will create the HTML tags for the data and return as a string, print the string. Now in your JSP, invoke the custom tag wherever you need the text. Ofcourse you need to parameterize the tag to determine what to fetch/display at what place.

HTH

V

Vaishak Suresh
  • 5,735
  • 10
  • 41
  • 66
0

I feel your pain @EranMedan , still can't believe this isn't a feature of JSP. After years of wanting it, I wrote my own simple solution here to do what you (and I) want: https://stackoverflow.com/a/25575120/1607642

Community
  • 1
  • 1