简体   繁体   中英

Delaying Output of JSP Custom Tag?

I want to delay the output of a custom tag.

The reason being: I want to add a tag to the head of the document that will compile a list of styles and scripts to include in the page. The subsequent tags in the page would add to the list of elements and the list would be printed once the body of the page has been generated.

Is this possible or is there a better way to do it. (I don't want to have to know what links are going to be added during the page compilation.)

Thanks

With JSPContext pushBody() and popBody() you can get some control over the order of output.

<%
  Writer body = new StringWriter();
  out = pageContext.pushBody(body);
  // following code will write to 'body' and not to client
%>
...
<%
  out = pageContext.popBody();
  // normal output again
%>
...
<% // write the captured output %>
<%= body %>

Even though it works it might be better to work around as it is very confusing.

I have asked this question on a variety of sites and didn't get the answer I was looking for (although some were creative, Thanks!) so I ended up doing quite a bit of research on my own for the "best" way to do this. This is what I came up with:

I created three custom tags so my html would look like the following:

<html:page>
    <html:head>
        ...
    </html:head>
    <html:body>
        ...
    </html:body>
</html:page>

The page tag creates a variable in the REQUEST_SCOPE called "headercontents" in the doStartTag() method that can compile a list of output that I want to place in the head of the document.

The head element simply adds all of its body contents to this variable.

The body element does nothing as of now, just has a tag file with a simple .

Any element in the body can now use the "headercontents" variable to post information to the head of the html page. (Thus linking any stylesheets or scripts that it needs in the head rather than in the body).

Then finally in the page tag's doEndTag() method it prints the contents of the "headercontents" variable then prints the contents of itself (the contents of the html:body tag).

The result is that the document can load and rearrange itself as needed. This is still a rudimentary version but I'll perfect it and post the source code sometime in the future.

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