Question

i have several common elements (components), that will generate some html. it seems my options are creating a taglib, or just putting that logic into a jsp page and including the jsp.

whats the difference? positives vs negatives?

Was it helpful?

Solution

When you use a taglib the container typically:

  • Writes and calls a helper method from within _jspService
  • Inside the helper method an instance of the tag class is created and standard methods are called (setParent(), doStartTag(), doEndTag() etc...)

This keeps all the code within the same resource (the request does not get passed on to another component) and hence allows you to build in looping behaviour and access other components on the current page.

There is overhead in learning Tag Libraries. But once you have got your first tag working its all downhill. Also the end result will be easier for non-developers to understand (assuming you choose good names for the tags).

OTHER TIPS

Taglibs allow you to define (typed) parameters which you can document. Also taglibs can be aware of their location in the object tree so act differently in a different context; or call a specific template over and over again to create iterators or statement constructs.

Are you aware that taglibs don't necessarily have to be written in Java? There is also a concept called tagfiles which allows you to write your taglib in JSP; often more suitable for flat compononents... quite close to includes.

Tags (which include the easy-to-use JSP-like tag file mechanism) support invocation with strongly-typed, named parameters.

Another incredibly useful and surprisingly often overlooked feature of JSP tags is the the JspFragment attribute type. This allows you to pass a chunk of JSP code, as a parameter, into a tag to be invoked, perhaps repeatedly.

Includes lack these powerful parameterization features.

taglibs make it easier to define and handle parameters, but there's a significant overhead to developing them. Includes are simpler, but less powerful. Much depends on your style.

In my experience, people generally just use includes because they don't want to take the time to learn to create tablibs. Leading to a fair mess. As long as your team small and your includes not too complex, it's not too bad. But it is a code smell.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top