Search code examples
javajspjsp-tags

Extending JSP Custom Tags


How do you extend an existing JSP custom tag?

As you know, a custom tag consists of two parts, an implementation class and a TLD file. I can extend the parent custom tag's class, but how do you "extend" its TLD file? One obvious solution is to cut and paste it and then add my stuff, but I wonder if there's a more elegant solution like the way you extend a tiles definition in Apache Tiles.

Thanks.


Solution

  • I don't think you can extend an existing tag, but a similar approach is to use a common abstract superclass for two tag implementation classes:

    // define repetitive stuff in abstract class
    public  abstract class TextConverterTag extends TagSupport{
    
        private  final long serialVersionUID = 1L;
        private String text;
    
        public String getText(){
            return text;
        }
    
        public void setText(final String text){
            this.text = text;
        }
    
        @Override
        public final int doStartTag() throws JspException{
            if(text != null){
                try{
                    pageContext.getOut().append(process(text));
                } catch(final IOException e){
                    throw new JspException(e);
                }
            }
            return TagSupport.SKIP_BODY;
        }
    
        protected abstract CharSequence process(String input);
    
    }
    
    // implementing class defines core functionality only
    public  class UpperCaseConverter extends TextConverterTag{
        private  final long serialVersionUID = 1L;
    
        @Override
        protected CharSequence process(final String input){
            return input.toUpperCase();
        }
    }
    
    // implementing class defines core functionality only
    public  class LowerCaseConverter extends TextConverterTag{
        private  final long serialVersionUID = 1L;
    
        @Override
        protected CharSequence process(final String input){
            return input.toLowerCase();
        }
    }
    

    But I'm afraid you will have to configure each tag class separately, as I don't think there are abstract tag definitions in taglibs.