Introduction: Scriptlet is a good choice for fast and miscellaneous (Fast-and-dirty) coding, but in the long run you need to choose a less cluttered solution for your JSP pages. In this issue of JSP best practices, Brettmclaughlin shows you how to convert Scriptlet into a JSP custom tag and then use it in your JSP development.
In the previous issue of JSP best practices, you learned a scriptlet based technique that was used to add the last modified timestamp to the JavaServer Page (JSP) file. Unfortunately, Scriptlet will introduce more long-term complexity into your page than the short-term benefits it offers. These scriptlet are mixed with various types of HTML in Java code, making debugging and design of the program extremely complex. Scriptlet cannot be reused, which often leads developers to copy-paste operations between JSP pages, leading to multiple versions of the same code. Also, Scriptlet makes error handling more difficult because the JSP does not provide a neat way to report script errors.
So this time we're going to design a new solution. In this issue of JSP best practices, you will learn some basics, mainly about how to convert scriptlet to custom tags and set them up for use in your JSP development project.
Why use Taglib?
The tag library is a library of tags that are used in JSP pages. The JSP container is launched with a small, default tag library. A custom tag library is a library that people put together for a particular purpose or purpose. Developers working together in a team may create very specific custom tag libraries for their projects, as well as create a generic custom tag library for current use.
The JSP tag replaces the scriptlet and relieves all the headaches that are incurred by Scriptlet. For example, you can see a tag like this:
<store:shoppingcart id= "1097629"/>
Or a tag like this:
<tools:usagegraph/>
Each tag contains a reference to a Java class, but the code in the class is still where it should be: a compiled class file outside of the tag.
From Scriptlet to tag
The first step in creating a custom tag is to decide how you want to use it, how to address it, and what attributes, if any, it is allowed to use or need. For timestamp tags, what we need is simple: a simple tag that can output the last modified data of a page.
Because no attributes are required, the tag looks like this:
<site-utils:lastmodified/>
The name of the tag is the same as the prefix: it's all site-utils. The content of the element is empty, which means that no child elements are allowed in the element. After defining this tag, the next step is to implement its behavior.