Taglib Design
[Overview]
Taglib is a relatively advanced JSP technology. As a JSP developer, it is acceptable not to understand taglib. Because the JSP style or Java style is concise and beautiful. If the technology is too complex or cumbersome, it will lose itself in the vast ocean of technology.
However, when our projects become larger and larger, or the Team has accumulated some technical skills, we naturally need to increase our development work to a higher level. When we face some very similar interfaces orProgramUnit, we will think of using such work results directly for the next project. This problem can be solved by taglib.
So far, we have not really explained what taglib is. As long as you have worked in JSP development, you have used taglib. It is used without knowing it. You will not forget the <JSP: Include/> tag. This is actually a taglib. The taglib literal translation is used as the tag library, which is defined by JSP for developers to use their own tag system. That is to say, developers can use their own special tags in JSP. The tag can be used for a specific purpose. For example, display the company copyright information required for each page. You do not need to copy and paste the sameCodeGo to each page.
However, the work that taglib can do is far more than that. Since each custom tag must be a full Java class, we can define a rich set of behaviors and control it through custom attributes.
[Instance]
I am used to using instances to illustrate the problem. You may be familiar with the user session status check. After a user logs on to the system, we want to automatically maintain the user's logon status. This process must be implemented in every program unit that requires user authentication to access. We usually need to access the predefined session server variable. When the variable does not meet a certain value, it is determined that the user is changed to illegal access or the session status is lost.
Let's take a look at how taglib is implemented. We need to write a tag that only processes the logic. The simplest logic is to check the user status session value. If the value does not meet a certain value, the user is redirected to a preset error page.
The following is the source code (checksessiontag. Java ):
(Omitted details)
Public class checksessiontag extends tagsupport
{
Public Int Doendtag ()
{
Try
{
String member_id = (String) pagecontext. getsession (). getattribute ( " Member_id " );
If (Member_id = Null | Member_id.equals ( "" ))
{
Pagecontext. Forward ( " /Home/check_session_fail.jsp " );
}
}
Catch (Exception E)
{
// The report exception process is omitted.
}
Return Eval_page;
}
}
[Analysis]
In the above source code, we have enabled the tag to automatically check the "member_id" value in the user session variable. If this value is null, we immediately determine that the user has no access permission, direct the process to a preset error page:/home/check_session_fail.jsp.
The class checksessiontag is derived from: tagsupport (javax. servlet. jsp. tagext. tagsupport). It is a Class Library supported since Java 1.3 and is located in the servlet. jar package. The description in the Java document is as follows:
A base class for defining new tag handlers implementing tag. the tagsupport class is a utility class intended to be used as the base class for new tag handlers. the tagsupport class implements the tag and iterationtag interfaces and adds additional convenience methods including getter methods for the properties in tag. tagsupport has one static method that is already ded to facilitate coordination among cooperating tags. using tag handlers will extend tagsupport and only redefine a few methods.
(This class is the base class of all taglib. This class defines a series of interfaces for implementing tags .)
In the instance checksessiontag class, we only override the doendtag method. Nothing is output to its container: JSP page. However, this class is practical in practical applications.
The following are the clips taken from a JSP in a finished project:
<Logic: checksession/>
When we directly access this page by entering a URL, we are immediately taken to a page with a report that the user session status is lost or has not been logged on.
This saves us the habit of copying the same Scriplet to every JSP page. (In fact, you can also use a mode similar to intercept filter to handle this requirement ). This makes our development work reusable, Flexiable, and extendable. As you can imagine, if we want to change the logic of the check session, we can simply change the logic of the checksessiontag. In addition, we can add an attribute similar to target = admin to the logic: checksession tag to limit the regions that only Administrators can access. This is the basic process of component-based development.
How to implement it?
[Implementation process]
We need to do a series of work to introduce taglib into our project.
Web. xml
To enable the JSP parser to recognize that our taglib must be configured in Web. xml. Web. XML is located in the/WEB-INF directory.
Use specific syntax to configure our taglib:
Web. XML (fragment)
< Web-app >
< Taglib >
< Taglib-Uri > /WEB-INF/logic. TLD </ Taglib-Uri >
< Taglib-location > /WEB-INF/logic. TLD </ Taglib-location >
</ Taglib >
< Web-app >
This syntax tells the container where to find all the tags starting with logic.
TLD is short for taglib defination. That is, the taglib definition. This file defines the tag we use, how the Java class is loaded, and how the tag works. Let's take a look at the actual TLD:
Logic. TLD (segment)
<? XML version = "1.0" encoding = "ISO-8859-1" ?>
<! Doctype taglib
Public "-// Sun Microsystems, Inc. // dtd jsp tag library 1.2/EN"
Http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd" >
< Taglib >
< Tlib-version > 1.0 </ Tlib-version >
< JSP-version > 1.2 </ JSP-version >
< Short-name > Logic </ Short-name >
< Uri > /Taglibs/logic </ Uri >
< Tag >
< Name > Checksession </ Name >
< Tag-class > Mbajob. Common. tags. Logic. checksessiontag </ Tag-class >
< Body-content > Empty </ Body-content >
</ Tag >
We noticed that the taglib is marked in.
1. Short-name: the prefix name.
2. Uri: identifies the taglib name.
Tag:
1. Name: Mark name (prefix: After)
2. Tag-class: class name (including package name)
3. Body-content: indicates the content mode. If the tag has no content, it is empty.
Place logic. TLD in the/WEB-INF, which ensures that the compiled checksessiontag class can be accessed by the container. You can complete the configuration. Note that the configurations of different JSP containers may be different. The configuration in this article is based on resin 2.1.11
[Application]
Create a JSP page. Add the following pre-compilation command at the beginning of the source code: (page)
<% @ Taglib prefix = "logic" uri = "/WEB-INF/logic. TLD" %>
This command tells the compiler where to look for all the definitions of tags starting with logic.
Next, add the tag <logic: checksession/> at any location to work. After the tag is instantiated, The doendtag process is automatically executed, the session server variable value is checked, and the page is redirected.
[More in-depth: attribute]
Sometimes we want to customize tags. We still use checksession as an example: now we need to restrict two types of users to access the system:
Some parts only allow access by users with administrator permissions. In this way, we can further define it in <logic: checksession target = admin/>. This requires some additional logic in the checksessiontag class. The check process is very simple. It depends on the analysis of your security system. However, it is critical to write the target attribute to obtain the data from the class.
To add available attributes to tags, you need to do the following:
1. Add members and corresponding readers to the class:
Checksessiontag. Java (segment ):
Public class checksessiontag extends tagsupport
{
Private string target;
Public Void Settarget (string T)
{
This . Target = T;
}
Public String gettarget ()
{
Return This . Target;
}
Public Int Doendtag ()
{
}
2. Change logic. TLD:
.
< Tag >
< Name > Checksession </ Name >
< Tag-class > Mbajob. Common. tags. Logic. checksessiontag </ Tag-class >
< Body-content > Empty </ Body-content >
< Attribute >
< Name > Title </ Name >
< Required > True </ Required >
</ Attribute >
</ Tag >
Add an arrtibute node to the tag. The syntax is as follows:
Name: attribute name
Required: Required attribute
Fortunately, JSP internally interprets attribute as a Java class member and can be directly used without explicitly obtaining this value. That is to say, as long as the target = admin is specified in the tag, the checksessiontag automatically obtains this value when it is alive and can be directly used in the logic.
In this way, we can add any attribute to the tag.
[After getting started]
So far, I can write some similar simple tags. Complete different logic based on different requirements. When we develop a new tag, we add a tag sub-tag in logic. TLD. Set the corresponding type. If necessary, we can completely transplant the tags we have written to the second project for use, with only a few changes. The changes are only limited to JavaSource code.
In my practical experience with my team, most of the taglib applications are still designing a series of special UIS, such as selector similar to selecting provincial/municipal multi-level administrative areas. To embed too many Scriplet and scripts in HTML, we usually write them in the assembled tag. to form the consistent appearance of the entire application, we have designed a framework for assembling page diagrams. to output set data to JSP, we have designed a Renderer that can bind data. After a long period of work, we found that there were only a few HTML pages in the JSP page of our project, which were completely composed of taglib. In the end, our taglib is classified by layout, logic, element, and form, and a relatively large scale has been formed. We even completed part of the work completed by the Apache Struts framework. Even more flexible. The ideas accumulated in all these work even influenced my technical ideas on the. NET platform.
In order not to take too long, I am not going to make any further exploration in this article. This article only introduces some entry-level things of taglib. If you have time, you may write some advanced taglib design methods again.
[With ASP. NET web custom control]
It cannot be said that taglib is comparable with ASP. NET Web M control. But I used to put the two together. Because in some actual projects, I did find some commonalities between them. Sometimes some components are completely the same.
1. Both define the process when marking the output start tag and end tag.
2. Both can be used across applications.
3. The same HTML and script can be used.
In comparison, ASP. NET Web M control is more advanced. It can be accessed directly in the form of objects in the container. You can also define methods and events. That is, a control can be fully controlled.
Taglib also has advantages, such as nesting and low development costs. The most important thing is that taglib is fine, small, and lively as a Java product. They have excellent technologies of different styles.
reference document
taglib best practices (IBM developerworks Chinese site )
http://www-900.ibm.com/developerWorks/cn/java/j-jsp07233/