javajspjsp-tagsjsp-fragments

How to create a Macro/Snippet/HTML Fragment/Named section in JSP without using tags/includes/JSPFragments?


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?


Solution

  • 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