Introduction to JSP custom tag Development

Source: Internet
Author: User
Tags tld
Introduction to JSP custom tag Development

Generally, the following two packages must be referenced to develop JSP custom tags:

 

ImportJavax. servlet. jsp .*;

ImportJavax. servlet. jsp. tagext .*;

 

First, we need to get a general idea of the interface and class hierarchy involved in the development of custom tags (the simpletag interface and simpletagsupport class are newly introduced in jsp2.0 ).

 

Objective 1: To customize a simple tag for displaying user information in a table

 

:

Use this custom tag on the JSP page:

 

Assume that we have a userinfo JavaBean, you only need to call this tag to use this tag on the JSP page.

 

<! -- Create an instance for displaying userinfo (for testing data) -->

<%

Userinfo user =NewUserinfo ();

User. setusername ("xuwei ");

User. setage (33 );

User. setemail ("test@test.test ");

Pagecontext. setattribute ("userinfo", user );

%>

 

<! -- Set the user attribute for the tag to bind the userinfo object to be displayed -->

<CC: showuserinfo user ="$ {Pagination. userinfo}"/>

 

Development steps:

 

For simple tag development, we only need to implement the tag interface. For simplicity, we can directly inherit the tagsupport class that implements this interface.

 

1. Create a custom label class

 

Public Class Userinfotag ExtendsTagsupport {

PrivateUserinfo user;

 

@ Override

Public IntDostarttag ()ThrowsJspexception {

Try{

Jspwriter out =This. Pagecontext. getout ();

If(User =Null){

Out. println ("No userinfo found ...");

Return Skip_body;

}

Out. println ("<Table width = '500px 'border = '1' align = 'center'> ");

Out. println ("<tr> ");

Out. println ("<TD width = '000000'> Username: </TD> ");

Out. println ("<TD>" + User. GetUserName () + "</TD> ");

Out. println ("</tr> ");

Out. println ("<tr> ");

Out. println ("<TD> Age: </TD> ");

Out. println ("<TD>" + User. getage () + "</TD> ");

Out. println ("</tr> ");

Out. println ("<tr> ");

Out. println ("<TD> Email: </TD> ");

Out. println ("<TD>" + User. getemail () + "</TD> ");

Out. println ("</tr> ");

Out. println ("</table> ");

}Catch(Exception e ){

Throw NewJspexception (E. getmessage ());

}

Return Skip_body;

}

@ Override

Public IntDoendtag ()ThrowsJspexception {

Return Eval_page;

}

 

@ Override

Public VoidRelease (){

Super. Release ();

This. User =Null;

}

// Getter and setters

PublicUserinfo getuser (){

ReturnUser;

}

Public VoidSetuser (userinfo user ){

This. User = user;

}

}

 

2. Create the tag library description file in Web-INF. tdl (TAG library description)

 

<? XML version ="1.0"Encoding =UTF-8"?>

<Taglib version ="2.0"Xmlns =Http://java.sun.com/xml/ns/j2ee"

Xmlns: xsi =Http://www.w3.org/2001/XMLSchema-instance"

Xsi: schemalocation =Http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">

<Tlib-version> 1.0 </tlib-version>

<JSP-version> 2.0 </JSP-version>

<Short-Name> CC </short-Name>

<URI>/Mytaglib</Uri>

<Tag>

<Name> showuserinfo </Name>

<Tag-class> com. mytags. userinfotag </Tag-class>

<Body-content> Empty </body-content>

<Attribute>

<Name> User </Name>

<Required> false </required>

<Rtexprvalue> true </rtexprvalue>

</Attribute>

</Tag>

</Taglib>

 

3. Configure web. xml

 

<JSP-config>

<Taglib>

<Taglib-Uri>/Mytaglib</Taglib-Uri>

/WEB-INF/mytaglib. TLD </taglib-location>

</Taglib>

</JSP-config>

 

4. Import it in the header of the JSP page that requires this tag

 

<% @ Taglib uri = "/mytaglib" prefix = "cc" %>

 

5. Use (refer to the above steps)

 

Therefore, a simple JSP tag is developed

 

Label description:

The userinfotag class we created inherits the tagsupport class and implements the tag interface. the lifecycle of the tag interface is controlled by the container where it is located, for example:

 

Setpagecontext () injects the pagecontext of the JSP page to access the pagecontext attribute of the JSP page object in subsequent methods.

 

Setparent () sets the parent tag of this tag

 

Setattribute () injects the attributes in the tag into the attributes of this class. You do not need to implement it yourself, but you need to provide the get and set methods of the attributes.

 

Dostarttag () is called after tag attribute setting. If skip_body is returned, content in the tag is ignored. If eval_body_include is returned, the content of the TAG body is output.

 

The doendtag () is called before the end tag. The skip_page is returned to skip the output after the entire JSP page, and the remaining part of the eval_page execution page is returned.

 

Called at the end of the release () Lifecycle

 

Note:The Tag Buffer Pool is enabled by default in Versions later than tomcat4.1 (WebSphere and WebLogic do not do this), so the release () method (_ jspdestroy () is not executed after the tag is executed () in other words, no matter how many times the custom tag of the same JSP page exists, but not every tag will create a buffer pool for it, it must be determined based on parameters, for example:

<CC: userinfotag user = "..." />

<CC: userinfotag/>

In the preceding example, two Tag Buffer pools are created due to different parameters.

 

You can solve this problem by setting the tomcat configuration file:
Add the enablepooling parameter to % Tomcat % \ conf \ Web. xml and set it to false (do not cache custom labels ).

<Init-param>
<Param-Name> enablepooling </param-Name>
<Param-value> false </param-value>
</Init-param>
 

Clear % Tomcat % \ conf \ directory

Bytes -------------------------------------------------------------------------------------------------------------------------------

The tagsupport class has implemented and extended some methods for US (for example, in the above method, we can directly use the pagecontext object and call the parent tag getparent ), in general, we only need to rewrite dostarttag () and doendtag ().

 

TLD file description:

<! -- Version -->

<Tlib-version> 1.0 </tlib-version>

<JSP-version> 2.0 </JSP-version>

<Short-Name> CC </short-Name>

<Tag>

<! -Specify the tag name -->

<Name> showuserinfo </Name>

<! -Specify the full path of tag files -->

<Tag-class> com. mytags. userinfotag </Tag-class>

<! -- If the label body is not required, empty is set; otherwise, JSP is set. -->

<Body-content> Empty </body-content>

<! -Set attributes (if any) -->

<Attribute>

<! -Specify the tag name -->

<Name> User </Name>

<! -Whether it is required. If it is not required, it is null. -->

<Required> false </required>

<Rtexprvalue> true </rtexprvalue> <! -Whether expressions can be used in attributes -->

</Attribute>

</Tag>

 

 

Web. xml file description:

<JSP-config>

<Taglib>

<! --

URI path of the tag Library

<% @ Taglib uri = "/mytaglib" prefix = "cc" %>

Uri

-->

<Taglib-Uri>/Mytaglib</Taglib-Uri>

<! -TLD file location -->

/WEB-INF/mytaglib. TLD </taglib-location>

</Taglib>

</JSP-config>

 

 

Objective 2: To customize a tag similar to the reapter control in ASP. NET

:

 

Use this custom tag on the JSP page:

 

<! -- Create an instance (for testing data) that needs to display the JavaBean (userinfo) set -->

<%

List <userinfo> Users =NewArraylist <userinfo> ();

Users. Add (NewUserinfo ("zhangsan", 12, "Zhangsan@163.com "));

Users. Add (NewUserinfo ("Lisi", 22, "Lisi@sina.com "));

Users. Add (NewUserinfo ("wangwu", 33, "Wangwu@qq.com "));

Pagecontext. setattribute ("users", users );

%>

 

<! -- Bind a data source to a tag -->

<Table width ='500p'Border ='1'Align ='Center'>

<Tr>

<TD width ='123'> Username </TD>

<TD width ='123'> Age </TD>

<TD> email </TD>

</Tr>

<CC: repeater Var ="Item"Items ="$ {Pagination. Users}">

<Tr>

<TD >$ {item. Username} </TD>

<TD >$ {item. Age} </TD>

<TD >$ {item. Email} </TD>

</Tr>

</CC: repeater>

</Table>

 

Development steps:

 

To complete this control, we need to implement an iterative interface, that is, iterationtag. Because tagsupport also implements this interface, we inherit this class

 

1. Create a custom label class

 

Public Class Repeater ExtendsTagsupport {

Private CollectionItems;

Private IteratorIt;

PrivateString var;

 

@ Override

Public IntDostarttag ()ThrowsJspexception {

If(Items =Null| Items. Size () = 0)Return Skip_body;

It = items. iterator ();

If(It. hasnext ()){

Pagecontext. setattribute (VAR, it. Next ());

}

Return Eval_body_include;

}

@ Override

Public IntDoafterbody ()ThrowsJspexception {

If(It. hasnext ()){

Pagecontext. setattribute (VAR, it. Next ());

Return Eval_body_again;

}

Return Skip_body;

}

@ Override

Public IntDoendtag ()ThrowsJspexception {

Return Eval_page;

}

Public VoidSetitems (CollectionItems ){

This. Items = items;

}

Public VoidSetvar (string var ){

This. Var = var;

}

}

 

2. Create the tag library description file in Web-INF. tdl (TAG library description)

Because this file has been created in the target type, we only need to add the configuration of this tag.

 

<Tag>

<Name> repeater </Name>

<Tag-class> com. mytags. Repeater </Tag-class>

<Body-content>JSP</Body-content>

<Attribute>

<Name> items </Name>

<Required> false </required>

<Rtexprvalue> true </rtexprvalue>

</Attribute>

<Attribute>

<Name>VaR</Name>

<Required> true </required>

<Rtexprvalue> true </rtexprvalue>

</Attribute>

</Tag>

 

3. Configure web. XML (in target 1, modification is not required)

 

4. Import it in the header of the JSP page that requires this tag

<% @ Taglib uri = "/mytaglib" prefix = "cc" %>

 

5. Use (refer to the above steps)

 

Label description:

The iteration interface is used. The following is the process for containers to process this interface.

 

 

Supplement as in Objective 1: In doafterbody (), if the returned value is eval_body_again, this method will be re-executed.

 

Objective 3: Use bodytagsupport

This goal will not be displayed using actual examples. It mainly explains why and when the bodytag interface or bodytagsupport class should be used?

If we need .... </Test> some labels or other processing are added to the header and tail of the label body. The general processing method is in the dostarttag and doendtag methods, but if it is an iteration tag, each segment of the label body must be marked at the header and tail each time during loop output. We can easily use bodytagsupport,

 

This interface has one more eval_body_buffered returned value in the dostarttag () method. It will calculate the subject and output it to the buffer (note: the buffer is not directly output to the client, we need to manually (this. bodycontent. getenclosingwriter (). write (this. bodycontent. getstring ();) to call the output client. Otherwise, the body content is not displayed)

 

Label description:

Description of the bodytagsupport Interface

 

Objective 4: custom function libraries

1. Create a function library class

 

Public ClassMyfunctions {

Public StaticString formatmyname (string name ){

Return"Your name is" + name;

}

Public Static IntAdd (IntA,IntB ){

ReturnA + B;

}

}

 

2. Configure in the TLD file (reference to the TLD file in target 1)

<Function>

<Name> formatmyname </Name>

<Function-class> com. taglib. myfunctions </function-class>

<Function-signature> JAVA. Lang. String formatmyname (Java. Lang. String) </function-signature>

</Function>

 

<Function>

<Name> Add </Name>

<Function-class> com. taglib. myfunctions </function-class>

<Function-signature> JAVA. Lang. String add (Int,Int) </Function-signature>

</Function>

 

3. Call in JSP

 

$ {CC: formatmyname ("wangfei ")}

$ {CC: add (12, 34 )}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.