Search code examples
jsptaglibcustom-tag

Defining custom JSP tags


I'm trying to create a custom JSP tag that uses other custom tags.

My approach was like so:

public int doAfterBody() throws JspTagException {
    BodyContent bc = getBodyContent();
    if (bc != null) {
        String body = bc.getString().toUpperCase();
        try {
            bc.clearBody();
            bc.getEnclosingWriter().write("<some-other-custom-tag>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return SKIP_BODY;
}

This does not seem to work because whatever I write using the BodyContent is not processed any more, so the output from the JSP still contains <some-other-custom-tag>. Is there a way to process the output before it ends up in the browser?


EDIT

I probably did not phrase my question very well. (I think) I'm aware of how the compilation works and how a request turns into a document.

As I understand it, the compiler goes over my JSP and finds <custom-tag>. It looks into a referenced TLD and finds the Java class associated with the tag. It invokes the class, sets parameters and stuff and then executes methods like doAfterBody() (depending on what type of tag handler the class extends). From there I'm writing <some-other-custom-tag> to the JSP's output. I understand that this doesn't work, because the compiler will not look over it again and therefor not realize that there's another custom tag to process.

I'm looking for a way to either (1) get the compiler to process (parts of) the output once again or (2) get the compiler to process a String object containing <some-other-custom-tag> so I can write that to the output.

I'm also open to any alternative solution, of course.


Solution

  • The text output from a custom tag should be text than can be understood by a browser (HTML, JavaScript, CSS, etc).

    That content is never parsed again because it wouldn't make too much sense: when the server knows that it should stop parsing that outputted content and send it to the browser? What would be the overhead of doing that?.

    What you can do is: whatever is done by that <some-other-custom-tag> is Java code anyway since JSP Tags are Java classes. I would refactor the tag classes to extend a common abstract one and then put that shared functionally in the latter so your both custom tags can access it.