Jsp custom tag

Source: Internet
Author: User
Tags tld

There is a mechanism in JSP that allows you to insert a tag similar to HTML in the JSP page. This article introduces the basic concepts and components of JSP custom tag, and how to develop and apply JSP custom tag.

What is tag
Using the HTML language, We can edit our webpage as follows:

<HTML>

<HEAD>

<TITLE>

HELLO WORLD

</TITLE>

</HEAD>

<BODY>

HELLO WORLD

</BODY>

</HTML>

Here we call </HEAD>, <TITLE>, and <BODY> a tag. HTML Markup is the control language for HTML documents. It is used to specify how the browser displays and prints documents. it is a phrase and symbol enclosed by a minor sign "<" and a minor sign ">, such as <Html> and </Body>. Many HTMl tags appear in pairs, such as <TITLE> </TITLE> and <Body> </Body>. In JSP, we can also customize our own tags for JSP pages, as shown in the following example:

<! -Login. jsp -->

<% @ Taglib uri = "/tlds/taglib. tld" prefix = "tagclass" %>

<Html>

<Head>

<Title> login </title>

</Head>

<Body>

<Tagclass: login width = "200" height = "100">

</Tagclass: login>

</Body>

</Html>

In the preceding example, </tagclass: login> is a JSP custom tag. Widtht and height are the attributes of the tag. <% @ Taglib uri = "/tlds/taglib. tld" prefix = "tagclass" %> is a tag library definition instruction, which will be discussed later. Custom tags in JSP are essentially a Java class with independent functions encapsulated in the form of tags. The use of tags reduces the Java code that is directly embedded into JSP pages, facilitates page layout, facilitates code reuse, and improves development efficiency.

Process of parsing tags on JSP servers
After a tag is embedded into a JSP page, how does the JSP server parse the tag? The meanings of each object are as follows:

Client: indicates the Client.

JSP-Server: JSP Server.

JSP-Page: JSP Page.

TLD: Mark database description files, define various attributes of tags and tags, and process files.

TagClass tag Handler

When a user accesses a JSP page, the request is sent to the JSP server. The JSP server calls the corresponding page according to the request. If the page contains a custom tag, the JSP service will access the TLD according to the page instruction <% @ taglib> to obtain information about the processing program, then call the constructor method of the processing program to start the marking processing program, and read the tag attributes and corresponding values. Call the corresponding set method for each object that does not have any attribute set. When a tag is used for the first time, no attribute is set. Therefore, the set method is called for each attribute. After the attribute is set, the JSP server calls the doStartTag () of the handler and then calls the doEndTag () method. Finally, the JSP server will continue to process the remaining pages and call release at the end of the page.
() Method to clear all occupied resources.

TLD File
TLD (TLD: Tag Library Descriptor) file, a Tag definition file in standard XML format, used to store Tag information. Below is a typical TLD file.

<? Xml version = "1.0" encoding = "ISO-8859-1"?>

<! -XML version and Character Set -->

<! DOCTYPE taglib

PUBLIC "-// Sun Microsystems, Inc. // dtd jsp Tag Library 1.1 // EN"

Http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd>

<! -Document Type Definition -->

<Taglib>

<! -This tag indicates that we begin to describe a tag library -->

<Tlibversion> 1.0 </tlibversion>

<! -Mark the database version -->

<Jspversion> 1.1 </jspversion>

<! -JSP version used -->

<Shortname> tagclass </shortname>

<! -Default name -->

<Tag>

<Name> login </name>

<! -Marked name -->

<Tagclass>

Tagclass. login. login

<! -Name of the corresponding class for processing the Tag -->

</Tagclass>

<Info>

<! -Description of the mark -->

</Info>

<Attribute>

<! -Start to define tag attributes -->

<Name> height </name>

<! -Attribute name -->

<Required> true </required>

<! -Indicates whether this attribute is required. -->

<Rtexprvalue> true </rtexprvalue>

<! -Indicates whether the property can be output using the JSP program segment -->

</Attribute>

<Attribute>

<Name> width </name>

<Required> true </required>

<Rtexprvalue> true </rtexprvalue>

</Attribute>

</Tag>

</Taglib>

The TLD file defines a tag library with only one tag. the login tag calls an Applet to verify the validity of the user. The class for processing this tag is tagclass. login. login. Width and height are two attributes of the tag. Attribute is the value sent as a parameter when a tag is used. We can add several tags in the preceding example or add several attributes for each tag. When developing a tag library, we do not have to start from scratch and write a brand new TLD. We can use an integrated development environment or modify the above example.

TagLib command
How does the JSP server define a tag library when parsing a tag? This is the main responsibility of the TagLib command.

Taglib command

Define a tag library and its custom tag prefix.

JSP syntax

<% @ Taglib uri = "URIToTagLibrary" prefix = "tagPrefix" %>

Example
<% @ Taglib uri = "/tlds/taglib. tld" prefix = "tagclass" %>

<Html>

<Head>

<Title> login </title>

</Head>

<Body>

<Tagclass: login width = "200" height = "100">

</Tagclass: login>

</Body>

</Html>

Description

<% @ Taglib %> the command declares that the JSP file uses a custom tag and references the tag library,

The prefix of their tags is also specified. You must use the <% @ taglib %> command before using the custom tag.

Attribute

Uri = "URIToTagLibrary": Uniform Resource Identifier (URI) uniquely names the custom tag Based on the tag prefix. URI can be a relative or absolute path.
Prefix = "tagPrefix": prefix before the custom tag. In the preceding example, </tagclass: login>

Tag handle)
Let's take an example to see how to implement a Tag handle. First, let's take a look at its class diagram:

Let's take a look at its code:

Package tagclass. login;

Import javax. servlet. jsp. tagext. TagSupport;

Import javax. servlet. jsp .*;

Import java. io .*;

Public class login extends TagSupport

{

Public login ()

{

Super ();

}

Public int doStartTag () throws JspTagException

{

JspWriter out = pageContext. getOut ();

Try

{

Out. println ("<applet codebase = applet/login/CODE = login. class width = 200 height = 100> </APPLET> ");

}

Catch (Exception e)

{

}

Return SKIP_BODY;

}

Publicc int doEndTag () throws JsptagException

{

Return EVAL_PAGE;

}

Public void release ()

{

Super. release ();

}

Public void setWidth (String language)

{

This. width = width;

}

Public String getwidth ()

{

Return this. width;

}

Public void setheight (string height)

{

This. Height = height;

}

Public String getheight ()

{

Return this. height;

}

Private string width;

Private string height;

}

From the above we can see that there are several requirements for implementing a simple tag handler: ① Add a class to inherit the java. servlet. jsp. tagext. tagsupport class. This class provides all the methods required by the java. servlet. jsp. tagext. Tag interface. In addition, some basic APIs are required to enable the JSP Container to call our own tag handler. ② A get <attribute> and set <attribute> method must be created for each tag attribute. jsp containers need to use these methods to pass parameters. ③ Create a constructor and self-destructor for the token handler. JSP needs to use the constructor to start the processing program. The self-destructor is defined in the realwritable () method. At the end of the life cycle of the processing program, you need to call the self-destructor to release the resources occupied. ④ Create two methods named dostarttag () and doendtag () to perform specific processing and output actions. These two methods are called when processing the start position and end position of the custom token. Their return values are in the tag
Static int defined in the interface. These static values are:

SKIP_BODY implicit 0: Skip the code between the start and end labels.

EVAL_BODY_INCLUDE implicit 1: output the body content to an existing output stream.

SKIP_PAGE implicit 5: Ignore the remaining page.

EVAL_PAGE implicit 6: continue to execute the following page

Of course, the identifier also has its own shortcomings. The encapsulation process is inconvenient and has limited functions. For some logic descriptions that are not complex and have a single function, it is much easier to use JSP tags when the parameter requirements to be passed are not high. For most commercial logic applications, bean is much better than servlet control.

Appendix: complete sample code used in the article
JSP code: login. jsp
<% @ Taglib uri = "/tlds/taglib. tld" prefix = "tagclass" %>

<Html>

<Head>

<Title> </title>

</Head>

<Body>

<Tagclass: login width = "200" height = "100">

</Tagclass: login>

</Body>

</Html>

Tag description Library: taglib. tld
<? Xml version = "1.0" encoding = "ISO-8859-1"?>

<! 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> tagclass </shortname>

<Tag>

<Name> login </name>

<Tagclass>

Tagclass. login. login

</Tagclass>

<Info>

</Info>

<Attribute>

<Name> height </name>

<Required> true </required>

<Rtexprvalue> true </rtexprvalue>

</Attribute>

<Attribute>

<Name> width </name>

<Required> true </required>

<Rtexprvalue> true </rtexprvalue>

</Attribute>

</Tag>

</Taglib>

Token handler: login. java
Package tagclass. login;

Import javax. servlet. jsp. tagext. TagSupport;

Import javax. servlet. jsp .*;

Import java. io .*;

Public class login extends TagSupport

{

Public login ()

{

Super ();

}

Public int doStartTag () throws JspTagException

{

JspWriter out = pageContext. getOut ();

Try

{

Out. println ("<applet codebase = applet/login/CODE = login. class width = 200 height = 100> </APPLET> ");

}

Catch (Exception e)

{

}

Return SKIP_BODY;

}

Publicc int doEndTag () throws JsptagException

{

Return EVAL_PAGE;

}

Public void release ()

{

Super. release ();

}

Public void setWidth (String language)

{

This. width = width;

}

Public String getWidth ()

{

Return this. width;

}

Public void setHeight (String height)

{

This. height = height;

}

Public String getHeight ()

{

Return this. height;

}

Private String width;

Private String height;

}

The Applet used in the tag handler: login. java
Import java. AWT .*;

Import java. AWT. event .*;

Import java. Applet .*;

Public class login extends applet implements actionlistener

{

Private string s_username;

Private string s_userpassword;

Private button B _ OK;

Private button B _register;

Private Label l_username;

Private Label l_userpassword;

Private textfield t_username;

Private textfield t_userpassword;

Private gridlayout g_gridlayout;

Public void Init ()

{

B _ OK = new button ("OK ");

B _register = new button ("register ");

Rochelle username = new label ("name ");

Rochelle userpassword = new label ("password ");

T_username = new textfield ();

T_userpassword = new textfield ();

B _ OK .addActionListener (this );

B _register.addActionListener (this );

G_gridlayout = new GridLayout (3, 2, 10, 10 );

This. setLayout (g_gridlayout );

// This. setBackground (Color. blue );

Add (l_username );

Add (t_username );

Add (l_userpassword );

Add (t_userpassword );

Add (B _ OK );

Add (B _register );

}

Public void actionreceivmed (ActionEvent ev)

{

String s_label = ev. getActionCommand ();

If (s_label.equals ("OK "))

{

T_username.setText ("name ");

}

If (s_label.equals ("register "))

{

T_userpassword.setText ("password ");

}

}

Public void paint (Graphics g)

{

}

}

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.