Use of custom tags in JSP

Source: Internet
Author: User
Tags definition character set constructor continue end html tags interface string
Js

Summary
There is a mechanism in JSP that allows you to insert markup similar to HTML in a JSP page. This article describes the basic concepts and composition of JSP custom tags, and how to develop and apply JSP custom tags.

Key words
JSP,XML,TLD, Marker

What is a tag
Using the HTML language we can edit our web pages like this:

<HTML>

<HEAD>

<TITLE>

HELLO World

</TITLE>

</HEAD>

<BODY>

HELLO World

</BODY>

</HTML>

Here we call </HEAD>,<TITLE>,<BODY> tag. HTML markup (HTML Markup) is the control language for HTML documents that specifies how browsers display and print documents. It is a phrase and symbol that is enclosed in less than "<" and greater than ">", such as <Html>, </Body>, and so on. Many HTML tags appear in pairs, such as <TITLE></title>, <Body></Body>, and so on. In the JSP we can also customize our own tags for JSP pages to use, as shown in the following example

<!-login.jsp-->

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

<title>login</title>

<body>

<tagclass:login width= "height=" >

</tagclass:login>

</body>

In the example above, </tagclass:login> is a JSP custom tag. WIDTHT, height is the attribute of this tag. <%@ taglib uri= "/tlds/taglib.tld" prefix= "Tagclass"%> is a tag library definition directive, which we will discuss later. Customizing the tag in the JSP essentially encapsulates a Java class that has a separate function in the form of markup. The use of tags reduces the direct embedding of JSP page Java code, facilitate the layout of the page, and facilitate the reuse of code, improve the efficiency of development.

The process of the JSP server parsing markup
So when a tag is embedded in a JSP page, how does the JSP server parse the tag? The meanings of each object are as follows:

Client: Represents clients.

jsp-server:jsp server.

Jsp-page:jsp page.

TLD: Tag library description file, defining various attributes and processing files for tags and tags.

Tagclass Tag Handler

When a user accesses a JSP page, the request is sent to the JSP server, the JSP server will be based on this request to call the corresponding page, if the page has a custom tag, JSP service will be based on the page instructions <%@ taglib> To access the information about the handler for the TLD, call the handler's constructor method, start the tag handler, and read the tag's properties and corresponding values. Call the appropriate set method for each property that is not set. When a marker is used for the first time, any of its properties are not set, so the set method is called for each property. After the property is set, the JSP server invokes the handler's doStartTag (), and then calls the Doendtag () method. Finally, the JSP server will continue to process the remaining pages, calling the release () method at the end of the page to clean up all the resources occupied.

TLD file
The TLD (Tld:tag Library descriptor Tag Library descriptor) file, a standard XML-formatted tag definition file, is used to hold information about the tag, and the following is a typical TLD file.

<?xml version= "1.0" encoding= "Iso-8859-1"?>

<!-xml's version and its 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 started to describe a tag library-->

<tlibversion>1.0</tlibversion>

<!-the version of the tag library-->

<jspversion>1.1</jspversion>

The version of the JSP used by the <!--->

<shortname>tagclass</shortname>

<!-the default name-->

<tag>

<name>login</name>

The name of the <!-tag-->

<tagclass>

Tagclass.login.login

<!-the name of the corresponding class that handles this tag-->

</tagclass>

<info>

<!-the description of this marker-->

</info>

<attribute>

<!-start defining the properties of the tag-->

<name>height</name>

The name of the <!-property-->

<required>true</required>

<!-Indicates whether this attribute is necessary-->

<rtexprvalue>true</rtexprvalue>

<!-Indicates whether this attribute can be exported with the results of the JSP's program segment-->

</attribute>

<attribute>

<name>width</name>

<required>true</required>

<rtexprvalue>true</rtexprvalue>

</attribute>

</tag>

</taglib>

In this TLD file, a tag library with only one tag is defined, and the tag named login invokes an applet to verify the legality of the user. The class that handles this tag is tagclass.login.login. Width and height are the two attributes of this tag. property is a value that is sent as a parameter using the tag characters. We can add a few tags to the example above, or we can have several attributes added to each tag. When we develop tag library, we do not have to start from scratch and write a new TLD ourselves. We can use an integrated development environment, or we can modify the example above.

Taglib directives
So when the JSP server parses a tag, how does it define a tag library? This is the main responsibility of the TAGLIB directive.

Taglib directives

Defines a tag library with a prefix for its custom tags.

JSP syntax

<%@ taglib uri= "uritotaglibrary" prefix= "TagPrefix"%>

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

<title>login</title>

<body>

<tagclass:login width= "height=" >

</tagclass:login>

</body>

Describe

<% @ taglib%> directive declares that the JSP file uses a custom tag and references the tag library.

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

Property

Uri= "uritotaglibrary": Uniform Resource Identifier (URI) uniquely name a custom tag based on the prefix of the tag, and the URI can be a relative or absolute path.
Prefix= "TagPrefix": the prefix before the custom tag. As in the above example, the </tagclass:login>

handler for the tag (tag handle)
Let's take an example to see how to implement a tag handle. The first is to look at its class diagram:

Let's take a look at its code again:

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;

}

As we can see from the above, there are several requirements for implementing a simple tag handler: ① adds a class that inherits Java. Servlet.jsp.tagext.TagSupport class. This class provides java. Servlet.jsp.tagext.Tag all the methods required by the interface. In addition, you need to use some basic APIs to enable the JSP container to invoke the tag handlers that we provide ourselves. ② must create a get<attribute> and set<attribute> method for each of the tag attributes, which the JSP container needs to pass parameters with. ③ to create a constructor and a self-destruct for the tag handler. The JSP needs to start the handler using the constructor. The self-destruct is defined in the Realease () method. At the end of the lifecycle of the handler, you need to invoke the resource that the self-destruct frees up. ④ creates two methods named doStartTag () and Doendtag () to perform specific processing and output actions. The two methods are called at the start and end positions of the custom marker. Their return value is the static int defined in the tag interface, which are the following static values:

Skip_body implicitly 0: Skips the code between the start and end tags.

Eval_body_include implied 1: The content of the body is exported to the existing output stream

Skip_page implicitly 5: Ignores the remaining pages.

Eval_page implied 6: Continue to the following page

Of course the marker also has its own drawbacks. Very inconvenient encapsulation process, limited functionality. For some less complex and functional single logical description, the need to pass the parameter requirements are not high, the use of JSP tags, more convenient. For most business logic applications, it is much better to use beans, and it is also appropriate for servlet control.

Appendix: The complete code for the example used in the article
JSP code: LOGIN.JSP
<%@ taglib uri= "/tlds/taglib.tld" prefix= "Tagclass"%>

<title></title>

<body>

<tagclass:login width= "height=" >

</tagclass:login>

</body>

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>

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

}

Applet:login.java used in the tag handler
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");

L_username= New Label ("name");

L_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 actionperformed (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.