javajspjstljava-ee-5

How to include another jsp page from custom jsp tag


I want to have a custom Jsp tag with one string attribute, if this is a a path to another jsp file then I want to include that JSP in the page (behave as a jsp:include); if not, then I want to just output the string in the body of the page.

I don't know how to do the jsp:include part...

I see there's a setJspBody in SimpleTagSupport that I can pass a JspFragment... But I don't know how to get that... I was hoping to find something like an IncludeTag class in javax.servlet.jsp that I could just delegate this logic to, like so setJspBody( new IncludeTag(...).getJspFragment() ) but I don't find what class implements the jsp:include functionality in the docs.


Solution

  • I used PageContext.include

    public class MyIncludeTag extends TagSupport {
       private String page;
       //getters setters
       @Override
       public int doStartTag() throws JspException {
         try {
                pageContext.include(page);
            } catch (ServletException | IOException e) {
                throw new JspException("Failed to include " + page, e);
            }
            return super.doStartTag();
       }
    }