Reputation:
I wonder how can I insert some JSP fragment into the BodyContent before it is evaluated? I've tried different methods, none of them worked. I must be doing something wrong.
For example, I want someone to use my tag as:
<mytag:html>
<mytag:head>
<link href="test.css"></link>
</mytag:head>
then it can insert a jsp fragment (read from config file) right after the head:
<link href="<%=request.getAttribute("theme")%>/test.css"/>
and it would finally output:
<html>
<head>
<link href="target-theme/test.css"></link>
<link href="test.css"></link>
</head>
Here is what I want to do:
I want to simplify the JSP development of other team member by just using <myTag:*/>
And I don't want to hardcode some HTML output in MyTag.Java. That's why I want to read some JSP fragment from an external file and inject it at runtime.
Any example/snippet for how to achieve this by using TagSupport?
Upvotes: 2
Views: 1904
Reputation: 24590
JSP files are transformed to servlets and at that point the invocation code for the JSP tags is also generated. Basically the servlet container instantiates your tags, sometimes using a pool of tag instances, but either way these instances are not directly exposed by the container.
Inside the tag handlers there is no concept of JSP code. The tag handlers are "closer to the metal" (so to speak) and here you can only write directly to the response. You can't evaluate JSP code. The body content is already evaluated at this point.
So you can't inject JSP fragments into your tag handlers, but you can have the tag handlers themselves pull content from that external file. But it would be static content!
Things like <%=request.getAttribute("theme")%>
will have no meaning here and will get sent directly to the client (as is). You could have some sort of JSP code in there if you limit yourself to EL expressions like ${theme}
that you could evaluate yourself, but this will get very complicated very fast as your external code will get more complex.
Depending on what you want to do, or what specification your servlet container implements, one other solution could be to use the JSP 2.0 tag files, so see if that could help given your situation (it would have been nice if JSPFragments could be built by the developer but unfortunately that's container implementation).
But what you are doing really sounds to me as decorating the output of other JSP code. If you want to simplify the development and add stuff later on top of its output, then also checkout SiteMesh. It is a web-page layout and decoration framework who can do what you are trying to achieve (and even more than that).
Upvotes: 1