JSP Custom Labels

Source: Internet
Author: User
Tags tld

Getting started with JSP Custom label development
Getting started with JSP Custom label development

In general, developing a JSP custom label requires referencing the following two packages

Import javax.servlet.jsp.*;

Import javax.servlet.jsp.tagext.*;

First we need to get an overview of the interfaces and classes involved in developing custom tags (where the Simpletag interface and the Simpletagsupport class are newly introduced in JSP2.0).

Goal 1: Customize a simple label that displays user information in a table

Use this custom label on the JSP page:

Assuming we have a userinfo JavaBean, then using this tag on a JSP page is just a matter of calling this tag

<%userinfo user = new UserInfo () user.setusername ("Xuwei"); User.setage ("[email user.setemail]"); Pagecontext.setattribute ("userinfo", user);  %><!--Set the user property bindings for the tag UserInfo object  --><cc:showuserinfo user= "${pagescope.userinfo}"/>

Development steps:

The development of simple label we just have to implement the tag interface, for the sake of simplicity you can directly inherit the TagSupport class that implements this interface.

1 Creating a Custom Label class

public class Userinfotag extends TagSupport {

Private UserInfo user, @Overridepublic int dostarttag () throws Jspexception {try {jspwriter out = This.pagecont        Ext.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= ' 20% ' >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 new jspexception (e.gEtmessage ()); } return skip_body;} @Overridepublic int Doendtag () throws jspexception {return eval_page;}    @Overridepublic void Release () {super.release (); This.user = null;} Getter and Setterspublic UserInfo GetUser () {return user;} public void SetUser (UserInfo user) {this.user = user;}

}

2 Create a tag library description file in Web-inf. TDL (Tag libraries Description)

<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" >

1.0

2.0

Cc

/mytaglib

<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>

3 Configuring Web. Xml

<taglib>    <taglib-uri>/mytaglib</taglib-uri>    <taglib-location>/web-inf/ Mytaglib.tld</taglib-location></taglib>

4 in the header of a JSP page that needs to use this tag

%@ taglib uri= "/mytaglib" prefix= "CC"%

5 use (refer to the above steps)

Sincerely, a simple JSP tag development completed

Label class Description:

The Userinfotag class we created inherits the TagSupport class, and it implements the tag interface, and the tag interface's lifecycle is controlled by the container in which it resides, such as:

Setpagecontext () injects the PageContext of the JSP page in order to have access to the PageContext property of the JSP Page object in a later method

SetParent () sets the parent label for this label

SetAttribute () injects attributes from the tag into this class's properties, without having to implement it yourself but to provide the property's get and set methods

doStartTag () is called after the start Tag property is set, and if return Skip_body ignores the contents of the label, the contents of the label body are output if Eval_body_include is returned

Doendtag () is called before the end tag, and returns Skip_page skips the output after the entire JSP page, returning Eval_page to perform the remainder of the page

Release () called at the end of the life cycle

Special Note: The tag buffer pool (WebSphere and WebLogic do not do so) is turned on by default in the version after tomcat4.1, so the release () method (_jspdestroy () is not released when the label is executed). That is, the same JSP page custom label no matter how many times there will only be one instance, but not every label will create a buffer pool for it, to be judged by parameters, for example:

In the example above, two tag buffer pools are created because of different parameters.

This problem can be resolved by setting the Tomcat configuration file:
Add the enablepooling parameter to%tomcat%\conf\web.xml and set it to False (the custom label is not cached).


Enablepooling
False

Emptying the%tomcat%\conf\ directory

The TagSupport class has implemented and extended some methods for us (for example, in the above method we can directly use the PageContext object, call the parent tag getparent (), etc.), so we simply rewrite doStartTag (), Doendtag () can be

TLD File Description:

1.0

2.0

Cc

<name>showUserInfo</name>

<tag-class>com.mytags.UserInfoTag</tag-class>
<body-content>empty</body-content>

<attribute>

<name>user</name>

<required>false</required>

True

</attribute>

Web. xml File Description:

<taglib>
<taglib-uri>/mytaglib</taglib-uri>

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

Goal 2: Customize a label similar to the Reapter control in ASP.

Use this custom label on the JSP page:

<%

list<userinfo> users = new arraylist<userinfo> ();   Users.add (New UserInfo ("Zhangsan", "[email protected]"), Users.add (New UserInfo ("Lisi", "[email protected]")); Users.add (New UserInfo ("Wangwu", "[email protected]"));p Agecontext.setattribute ("Users", users);

%>

UserName Age Email
${item.username} ${item.age} ${item.email}

Development steps:

To complete this control we need to implement an iterative interface, Iterationtag, because TagSupport also implements this interface, so we inherit this class

1 Creating a Custom Label class

public class Repeater extends TagSupport {

Private Collection items;private Iterator it;private String var; @Overridepublic int doStartTag () throws Jspexception {
   if (items = null | | items.size () = = 0) return skip_body;    it = Items.iterator ();      if (It.hasnext ()) {        Pagecontext.setattribute (Var, it.next ());    }    return eval_body_include;} @Overridepublic int Doafterbody () throws Jspexception {    if (It.hasnext ()) {        Pagecontext.setattribute (Var, It.next ());        return eval_body_again;    }    return skip_body;} @Overridepublic int Doendtag () throws Jspexception {    return eval_page;} public void Setitems (Collection items) {    this.items = items;} public void SetVar (String var) {    This.var = var;}

}

2 Create a tag library description file in Web-inf. TDL (Tag libraries Description)

Since this file has been created for Target 1, we only need to add this label configuration

<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>

3 Configuring Web. XML (completed in target 1 without modification)

4 in the header of a JSP page that needs to use this tag

%@ taglib uri= "/mytaglib" prefix= "CC"%

5 use (refer to the above steps)

Label class Description:

We used the iterative interface, and the following is the process by which the container handles this interface

As a supplement to Goal 1: in Doafterbody () if the return value is Eval_body_again then this method will be re-executed

Target 3: Use Bodytagsupport

This goal does not show up with real-world examples, mainly explaining why, in what cases, you need to use the Bodytag interface or the Bodytagsupport class?

If we need to be in .... Between the head and tail of the label body with some marks or other processing, the general method is done in the doStartTag and Doendtag methods, but if it is an iterative label, each piece of content in the label body in the loop output each time in the head and tail to add some markers, It's very convenient for us to use Bodytagsupport.

This interface has a eval_body_buffered in the doStartTag () method return value, which evaluates the body and outputs it to the buffer (note: This is where the buffer is not output directly to the client, Requires us to manually (This.bodyContent.getEnclosingWriter (). Write (this.bodyContent.getString ());) to make a call to the output client, otherwise the principal content will not be displayed)

Label class Description:

Notes on the Bodytagsupport interface

Goal 4: Custom Library of functions

1 Creating a Function library class

public class Myfunctions {

public static string Formatmyname (string name) {   return ' your name is ' + name;} public static int Add (int a, int b) {   return a+b;}

}

2 configuration in TLD files (for TLD files in Target 1)

<function-signature>java.lang.string formatmyname (java.lang.String) </function-signature>< Function-class>com.taglib.myfunctions</function-class><function-signature>java.lang.string Formatmyname (java.lang.String) </function-signature>

<function-signature>java.lang.string Add (int, int) </function-signature><function-class> com.taglib.myfunctions</function-class><function-signature>java.lang.string Add (int, int) </ Function-signature>

3 called in JSP

${cc:formatmyname ("Wangfei")}

${cc:add (12, 34)}

JSP Custom Labels

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.