Creating Custom Tags in JSP
Java developers can now embed complex logic into middle-tier objects while exposing only simple, easy-to-use tags to the presentation layer. This frees Java developers to do what they do best while enabling presentation developers to focus on building good UIs.
Custom Tags are made up of two components:
a) Tag Handler Class – a simple java class that extends classes from package javax.servlet.jsp.tagext
b) Tag Library Descriptor- a simple xml file with extension tld and specifies the Tag Handler class, tag's Name and body. Let's jump into a simple code and it will be more clear as we go on:
Create a simple java class that extends javax.servlet.jsp.tagext.TagSupport class. This class has a method int doStartTag(){} which handles the business logic when the tag is called. This method should return the int type value. The probable values are:
1) SKIP_BODY: Instructs the JSP engine to ignore the body (if one exists) of this tag and not return it to the client
2) EVAL_BODY_INCLUDE: Instructs the JSP engine to evaluate and include the content of this tag's body and return it to the client
3) EVAL_BODY_AGAIN: Request the reevaluation of some body. Returned from doAfterBody. For compatibility with JSP 1.1, the value is carefully selected to be the same as the, now deprecated, BodyTag.EVAL_BODY_TAG.
Let's write some code for the tag:
Request the reevaluation of some body. Returned from doAfterBody. For compatibility with JSP 1.1, the value is carefully selected to be the same as the, now deprecated, BodyTag.EVAL_BODY_TAG.
Register the created Tag Class in a Tag Library Descriptor file (a simple xml file with extension .tld)
Now we are done with the Tag Handler class and the Tag Library Descriptor. Its time to use our created tags in a jsp file.
After building and deploying our application, the output will be something as shown below:
As we are done with the simple tag, it's time to move ahead with the tag with body. For a tag to have ability to deal with its body, it must extend javax.servlet.jsp.tagext.BodyTagSupport. Like TagSupport, BodyTagSupport also has a convenience class that defines default methods for the interface called BodyTag. A tag that implements BodyTag can parse the contents of its tag body and output anything based on that content The Tag Handler, TLD and the jsp files can be something like this:
Some configuration on the xml file:
Some changes on the jsp file:
Now lets use it in our jsp page, the output is simply predictable:
Tags with property
To make tags really useful we can have attributes in them and manipulate the output as per attribute's value.We need to add an attribute in the TagHandler class and add its mutator and accessor. The next step is including the attribute in our tld file. Let's jump into code:
Some changes in the xml file:
And in jsp:
Happy Coding!
No comments:
Post a Comment