简体   繁体   中英

How can we reuse JSP chunk defined within JSP Page; without creating another JSP file?

I have 14 piece of code at different places in JSP which is getting repeated at 14 places in JSP:

<div>
 <table>
    <tbody>
        <tr>
            <td><spring:message code="economy"/></td>
            <td>${spm}</td>
       </tr>
       <tr>
            <td><spring:message code="nok"/></td>
            <td>${spm.nok}</td>
       </tr>
    </tbody>
 </table>
</div>

Requirement to define above chunk at one place and reuse 14 times.

I know i can create its .JSPF and include it again using <% include.

But we want to avoid this as i have to apply same for other chunks too and i am told not to make much files.

So is there any way to define JSP chunk inside page(somewhere in header or footer or in HTML element) and reuse at multiple places on load? Please ask if anything unclear in question

Update : Please also consider following while answering:

<c:forEach varStatus="loop" items="${economy}" var="spm"> 
  //Code Chunk spm.nok
</c:forEach>

<c:forEach varStatus="loop" items="${economy1}" var="spm"> 
 //Code Chunk spm.nok
</c:forEach>

您可以在不显示任何内容的索引页上添加此数据,并且每当要复制该div并使用jQuery或Javasscript粘贴时就可以添加。

Your requirement is pretty typical but interesting, ideal way is to make a JSP/JSPF with re-usable code and include it, like you have said.

I would recommend discuss with your folks and consider using JSP Templates or some other templating mechanism, but considering your requirement, I think your best bet can be:

<!DOCTYPE html>
<html>
<head>
    <script lang="javascript">
        var reusableHtml = "<div>  <table border='1'>    <tbody>        <tr>            <td>0</td>            <td>${spm}</td>       </tr>       <tr>            <td>A</td>            <td>B</td>       </tr>    </tbody> </table></div>";

        function pushReusbalecode(){
            alert('1');
            document.getElementById("demo1").innerHTML = reusableHtml;
            document.getElementById("demo2").innerHTML = reusableHtml;
        }

    </script> 
</head>
<body onload="pushReusbalecode()">

<div id="demo1"></div>

<br>##########################<br>

<div id="demo2"></div>

<br>##########################<br>

</body>        



</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM