I have been programming with JSP and ASP for a long time. Among these two server-side programming solutions, I increasingly feel that JSP is much more powerful than ASP. Why should I choose JSP as my preferred server-side web application development tool? Of course, JSP has many fascinating features and functions, but JSP's tag library was one of the most important reasons for me to make this decision.
Why do you say this? The reasons are twofold: maintenance and speed of development. Server-side scripting languages are actually the melting pot of Internet development. On a server page, you can easily mix various script methods and objects. This kind of page is simply the concrete for building the Web. It is this mixture of "stuff" that gives server-side scripts powerful information processing capabilities. It allows server-side programmers to develop dynamic and flexible Web pages. But, on the other hand, the free mixing of scripts also has its disadvantages, which is that it is very troublesome to maintain, especially as the size of the project continues to grow. To make matters worse, as the complexity of the code increases, the speed of development will slow down, which is not conducive to the development of medium-sized and large-scale web applications. Many medium-sized or large server-side web applications are launched very late and the cost is high. Uncontrollable. In addition, once developed, the site still needs to find qualified programmers to maintain these rather complex codes. As a result, these programmers become general web designers, and the server-side application plays a key role in both the final graphic design and implementation. It's weakened.
In order to overcome this problem, ASP introduced COM object technology, while JSP provided J2EE as a countermeasure. These solutions are built on mechanisms of centralized, reusable code bases. However, they are too difficult to use and take a lot of time to learn. Furthermore, these solutions do not reduce the temptation to create messy code, and as a result, we have to organize large, well-structured development teams to use these technologies. For medium-sized projects, such methods are usually less used, but in fact, medium-sized web application projects are the most common. As a result, many projects are forced to use a development and maintenance environment that does not meet their needs.
Fortunately, JSP provides a better way to solve this problem. Tag libraries provide an easy way to create reusable blocks of code. Once a tag library is designed, it can be used again in many projects. What's even more convenient is that, unlike COM and J2EE, as long as you know how to write JSP, you don't need to learn any other skills to create a tag library! Finally, tag libraries also improve the maintainability of web applications. This improvement in maintainability is reflected in the easy implementation of XML-based customizable interfaces on JSP pages. As a result, web designers can build JSP web applications without knowing what JSP is. In this way, Web development becomes a very efficient team development task. JSP programmers can create custom tags and back-end code modules, while Web designers can use custom tags and focus entirely on the Web design itself. The tag library solves the problem of code confusion and does it cleanly and beautifully (in fact, XML is the essence of solving these problems, but the tag library still plays a key role).
What is a tag library?
JSP tag library (also called custom tag library) can be seen as a method of generating XML-based scripts through JavaBeans. Conceptually, tags are simple and reusable code structures. For example, in our latest release of JSPKit (within JSP Insider), XML documents are easily accessed using XML tags. Please see List A below.
Listing A: Example tags that perform XML/XSL transformations and the HTML pages they contain
<%@ taglib uri=" http://www.jspinsider.com/jspkit/JAXP " prefix="JAXP"%>
<JAXP:TransformerTag>
<JAXP:XMLFile>c:/xml/example.xml</JAXP:XMLFile>
<JAXP:XSLFile>c:/xml/example.xsl</JAXP:XSLFile>
</JAXP:TransformerTag>
The above example uses simple tags to access the more powerful code behind the scenes. The tag part of the statement first loads an XML file and then applies an XSL file to transform the contents of the XML file into A certain representation format and sent to the client, all this is just using a very simple tag. Custom tags make it easy to create reusable open source modules in JSP projects, and all you need is a tag library and its documentation.
Important Features of Tag Library
1. Easy to install on multiple projects Tags can be easily migrated from one JSP project to other projects. Once you create a tag library, just package everything into a JAR file that you can reuse in any JSP project. Tag libraries are becoming increasingly popular because tags can be reused and can easily be used in your own projects. Currently, the best tag resource can be found at JSPTags.com.
2. Extended JSP tag library can have any features and functions in the JSP specification (JSP 1.2). You can extend and increase the functions of JSP without limit without waiting for the next version of JSP to appear. For example, you are not satisfied with the JSP include call. You can create your own include tags that enforce your own specifications.
3. Easy to maintain
The tag library makes JSP web applications very easy to maintain for the following reasons:
(1) Label application is simple and easy for anyone to use and understand.
(2) All program logic codes are concentrated in the tag processor and JavaBeans. This means that when you upgrade the code, you don't need to modify every page that uses the code. You only need to modify the centralized code files.
(3) If you need to add new functions, you do not need to modify any existing pages. You can add additional attributes to the tags to introduce new behaviors, while other old attributes remain unchanged, so that all old pages can still be used. Works normally. For example you have a label that makes all text blue:
<BlueText>My Text</BlueText>
But later in the project, you want the blue to be darker. You can keep the original label and just add a new attribute to it: shade, as shown below:
<BlueText shade="teal">My Text</BlueText>
All old tags can still produce blue text, but now you can use the same tag to produce darkened blue text.
(4) Labels improve code reusability. Code that has been tested and used many times will definitely have fewer bugs. Therefore, JSP pages using custom tags also have fewer defects and are naturally much more convenient to maintain.
4. Rapid development time tag library provides an easy way to reuse code. One of the standard ways to reuse code in server-side languages is to use templates. Compared to using template libraries, tag libraries are a better solution. With a template library, you have to modify the templates or build a strict interface for each project, while the tag library does not have these restrictions and has all the benefits of object-oriented, can be flexible and more extensible, and, by reusing code , you can spend less time doing development and more time designing your web application. The interface of the tag library is also very simple, making it very easy to insert, use and debug.
Tag structure
Although the tag library is very easy to use, the internal implementation mechanism of establishing a tag library is still quite complicated, at least more complicated than establishing a simple JavaBean. The complexity comes from the fact that the tag library is composed of several parts. However, you only need to master the knowledge of Java and JSP.
A simple tag consists of the following elements:
1. JavaBean: To get the benefits of Java and its inherent object-oriented nature, reusable code should be placed in a separate code container, which is a JavaBean. These JavaBeans are not an essential part of the tag library, but they are the basic code modules used by the tag library to perform the assigned tasks.
2. Tag Processor: The tag processor is the real heart of the tag library. A tag handler references any external resources it needs (JavaBeans) and is responsible for accessing JSP page information (PageContext objects). The JSP page passes the tag attributes set on the page and the content in the tag body to the tag processor. When the tag processor completes its processing, it will send the processed output results back to the JSP page for further processing. .
3. Tag library descriptor (TLD file): This is a simple XML file that records the attributes, information, and location of the tag processor. The JSP container uses this file to know where and how to call a tag library.
4. The web.xml file of the website: This is the initialization file of the website. In this file, the custom tags used in the website need to be defined, as well as the tld file used to describe each custom tag.
5. Release files (WAR or JAR files): If you want to reuse custom tags, you need a way to move them from one project to another. Packaging the tag library into a JAR file is a simple and effective way.
6. Tag library declaration on the JSP page: If you want to use a custom tag in the JSP page, you need to use the tag library identifier to declare it on the page.
It seems that there is a lot of work to be done, and of course it will be a little tricky when you first start using it, but it is not very difficult. The point is not about coding, but about organizing the pieces correctly. This hierarchical structure is important because it makes the use of tags flexible and easier to transfer. More importantly, these levels allow the entire process of creating a tag library to be automated through the JSP IDE (JSP integrated development environment). The JSP IDE can automatically complete most of the work of creating custom tags, and you only need to be responsible for setting up the code and tag processors yourself.
(Note: A tag processor only defines one custom tag; a tag library is a collection of several tag processors that handle the same task)
Create your first tag
The following will teach you step by step how to create a custom tag , a specific example is extending JSP so that it has its own HTML encoding function. This feature replaces all < and > characters with HTML code. It can be easily extended to do other encoding processing. To simplify, this example only explains the basic elements of creating a custom tag.
Any reusable part of the code
that creates a JavaBean
should be placed in a JavaBean.This is very important. This way you can reuse the code in other projects. Since any code placed inside a tag handler is not reusable outside the tag, it is important to isolate the reusable code portions. In this example, the logic coded for HTML is common and therefore placed in a JavaBean, see Listing B
Listing B: HTML-encoded JavaBeans
/* HTML_Format.java */
public class HTML_Format extends Object implements java.io.Serializable {
/** Create a new HTML_Format */
public HTML_Format() {}
/** Replace all < and > characters in a string with the response HTML encoding */
public String HTML_Encode(String as_data)
{
int li_len = as_data.length();
/*The length of the string buffer is longer than the original string*/
StringBuffer lsb_encode = new StringBuffer(li_len + (li_len/10));
/* Loop to replace all < and > characters*/
for(int li_count = 0; li_count < li_len; li_count++)
{ String ls_next = String.valueOf(as_data.charAt(li_count));
if (ls_next.equals("<")) ls_next = "<";
if (ls_next.equals(">")) ls_next = ">";
lsb_encode.append( ls_next );
}
return( lsb_encode.toString() );
}
}
The code for creating a tag processor is shown in Listing C:
Listing C: HTML encoding tag processor
import java.io.IOException;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class HTML_FormatTag extends BodyTagSupport
{
/* 1) This function will be called at the end of the tag*/
public int doEndTag() throws JspTagException
{
try
{ /* 2) Get the text in the label */
BodyContent l_tagbody = getBodyContent();
String ls_output = "";
/* 3) If the tag body has text, process it */
if(l_tagbody != null)
{ HTML_Format l_format = new HTML_Format();
/* 3a) Convert the content of the tag body into a string */
String ls_html_text = l_tagbody.getString();
ls_output = l_format.HTML_Encode(ls_html_text);
}
/* 4) Write the results back to the data stream */
pageContext.getOut().write(ls_output.trim());
}
catch (IOException e)
{ throw new JspTagException("Tag Error:" + e.toString());
}
/* Let JSP continue to process the content of the following pages*/
return EVAL_PAGE;
}
}
This processing is very simple, it includes:
1. Read the text between the opening and closing tags
2. Call html encoding function
3. Return the results to the JSP page.
Create a tag descriptor
We need to describe the custom tag so the system knows what to do with it. The suffix of this description file is .tld. The TLD file is usually named after the tag processor and is stored in the "/WEB-INF/" directory. See Listing D.
Listing D: HTML encoding tag descriptor <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
" http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd ">
<TAGLIB>
<TLIBVERSION>1.0</TLIBVERSION>
<JSPVERSION>1.1</JSPVERSION>
<SHORTNAME>HTML_FormatTag</SHORTNAME>
<URI></URI>
<INFO>HTML Encoding Tag </INFO>
<TAG>
<NAME>HTMLEncode</NAME>
<TAGCLASS>HTML_FormatTag</TAGCLASS>
<INFO>Encode HTML</INFO>
</TAG>
</TAGLIB>
Update the Web XML file
to now tell the JSP container how to use the tag library. To do this, you need to modify the web.xml file. Specifically, you need to add a taglib project to register the tag library and assign a URI to the tag. The URI is the only index on the Web site that applies to this particular tag. Since the tag may be used on different Web sites in the future, it is best to use the complete URL and/or package name to ensure uniqueness. This example is simplified; see Listing E for sample code.
Listing E: Modify the web.xml file <?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
" http://java.sun.com/j2ee/dtds/web-app_2.2.dtd ">
<WEB-APP>
<TAGLIB>
<TAGLIB-URI>
HTMLEncode
</TAGLIB-URI>
<TAGLIB-LOCATION>
/WEB-INF/HTML_FormatTag.tld
</TAGLIB-LOCATION>
</TAGLIB>
</WEB-APP>
Use new tags.
After the customized tags are set, you can use them on your JSP pages. To do this, just use the taglib directive command to declare the tags you want to use on the page. Tags are indexed by their unique URI, which is then assigned a namespace prefix. This prefix has no special meaning, as long as it does not conflict with other namespaces, it can be arbitrary. Please see Listings F and G below.
Listing F: Using the HTML encoding tag<%@ taglib uri="HTMLEncode" prefix="Examples" %>
on a JSP page
<PRE>
<?XML:NAMESPACE PREFIX = Examples /><Examples:HTMLEncode>
<Hello, Simple sample>
</Examples:HTMLEncode>
</PRE>
Listing G: Output of sample code<Hello, Simple sample>
which displays as:
<Hello, Simple sample>
With this tag, I encoded all the code of the page. All custom tags are processed on the server. This means you won't see custom tags on the output page.
As you can see, creating tags is not difficult. The most troublesome part is learning the whole ins and outs of tag processors. This is a powerful feature, and we've only scratched the surface. Because of the many steps involved in this process, new JSP programmers may find it confusing when creating tags.
Conclusion
The tag library is one of the most important features of JSP, and it is still under constant development. It is indeed a new thing, so it has not been widely adopted yet, but the custom tag library has stripped away its mystery, and more and more developers are starting to pay attention to and use it. In late 2001, it can be expected that tag libraries will be a very common feature in many JSP projects.
The benefits of tag libraries are only briefly discussed in this article. Tag libraries actually have many other powerful features. Tag libraries push JSP development into an unprecedented new world. This is indeed an exciting new technology for JSP developers because they get a tool that can convert JSPs into various applications and build any type of web application. The tag library turns JSP into the richest, most dynamic development capability, and powerful Web programming environment. Its capabilities are limited only by our imagination and creativity.