JSP 2.0 has a feature called "Tag Files", and you can write tags without external Java code and tld
. You need to create a .tag
file and put it in WEB-INF\tags
. You can even create a directory structure to package your tags.
For example:
/WEB-INF/tags/html/label.tag
<%@tag description="Rensders a label with required css class" pageEncoding="UTF-8"%>
<%@attribute name="name" required="true" description="The label"%>
<label class="control-label control-default" id="${name}Label">${name}</label>
Use it like
<%@ taglib prefix="h" tagdir="/WEB-INF/tags/html"%>
<h:label name="customer name" />
Also, you can read the tag body easily:
/WEB-INF/tags/html/bold.tag
<%@tag description="Bold tag" pageEncoding="UTF-8"%>
<b>
<jsp:doBody/>
</b>
Use it:
<%@ taglib prefix="h" tagdir="/WEB-INF/tags/bold"%>
<h:bold>Make me bold</h:bold>
The samples are very simple, but you can do lots of complicated tasks here. Please consider you can use other tags (for example: JSTL
which has controlling tags like if/forEcah/chosen
text manipulation like format/contains/uppercase
or even SQL tags select/update
), pass all kind parameters, for example Hashmap
, access session
, request
, ... in your tag file too.
Tag File are so easy developed as you did not need to restart the server when changing them, like JSP files. This makes them easy for development.
Even if you use a framework like Struts 2, which have lots of good tags, you may find that having your own tags can reduce your code a lot. You can pass your tag parameters to struts and this way customize your framework tag.
You can use tags not only to avoid Java, but also minimize your HTML codes. I myself try to review HTML code and build tags a lot as soon as I see code duplicates start in my pages.
(Even if you end up using Java in your JSP code, which I hope not, you can encapsulate that code in a tag.)