Custom labels for JSP2

Source: Internet
Author: User
Tags getmessage sql error tld

The development of a tag library in a JSP requires only the following steps

1. Development of custom Label processing classes

2, create a *.tld file, each *.tld file corresponding to a tag library, each tag library can contain multiple tags

3. Using a custom label in a JSP file

Developing Custom Label Classes

When a simple tag is used on a JSP page, the underlying is actually supported by the label processing class, allowing complex functionality to be encapsulated with a simple label.

Custom label classes should inherit a parent class: Javax.servlet.jsp.tagext.SimpleTagSupport, in addition, JSP custom tags have the following requirements:

1. If the tag class contains attributes, each property has a corresponding getter and setter method

2, rewrite the Dotag () method, this method is responsible for generating the page content

The following is the simplest custom label to develop:

Helloworldtag.java

Package Com.baiguiren;import java.io.ioexception;import java.util.date;import javax.servlet.*;p ublic class Helloworldtag extends simpletagsupport{    //Override the Dotag () method, which generates page content for the label public    Void Dotag () throws Jspexception, IOException {        //Gets the page output stream and outputs the string        Getjspcontext (). Getout (). Write ("Hello world!" + New Date ());}    }

  

Creating TLD Files

The TLD is the abbreviation for the tag library definition, which is defined by the tag libraries, the suffix of the file is the TLD, each TLD file corresponds to a tag library, and a tag library can contain multiple tags. TLD files are also known as tag library definition files.

The root element of the tag library definition file is Tablib, which can contain multiple tag child elements, each of which defines a label. You can usually copy a tag library definition file under the Web container and modify it on that basis.

<?xml version= "1.0" encoding= "UTF-8"? ><taglib 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/http Java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd "    version=" 2.0 ">    <tlib-version>1.0</ tlib-version>    <short-name>mytaglib</short-name>    <uri>http://localhost:8080/jsp/ Mytaglib</uri>    <!--define the first label        --<tag> <description> output Hello, world</ Description>        <!--define label names--        <name>helloWorld</name>        <!--define label handling class--        <tag-class>com.baiguiren.HelloWorldTag</tag-class>        <!--define the label body as empty---        < body-content>empty</body-content>    </tag>    </taglib>

  

The tag library definition file above is also a standard XML file, the root element of which is the taglib element, so you can add the element directly each time you write the tag library definition file.

There are three sub-elements below the taglib:

1. Tlib-version: Specifies the version that the tag library implements, which is a build number that is an identity, and does not have much effect on the program.

2, Short-name: The default short name of the tag library, the name is usually not much use.

3. Uri: This property is very important, it specifies the URI of the tag library, which is equivalent to specifying a unique identifier for the tag library. When using the tag library in a JSP page, the tag library is positioned based on the URI property.

In addition, the taglib element can contain multiple tag elements, each tag element defines a tag that allows the following common child elements to appear under the tag element.

Name: This is the label, the child element is important, the JSP page is based on the name to use this tag.

Tag-class: Specifies the label's processing class, which specifies which label processing class the label is to handle.

Body-content: This child element specifies the content of the tag body, which can be a few of the following:

1, Tagdependent: Specify the label processing class itself is responsible for handling the label body

2. Empty: Specifies that the label can only be used as an empty label

3. Scriptless: Specifies that the label body can be a static HTML element, an expression language, but does not allow JSP script to appear.

4, JSP: Specify the label body of the tag can use JSP script (JSP2 specification no longer recommend using JSP)

Dynamic-attributes: Specifies whether the label supports dynamic properties. This child element is required only if the dynamic property label is defined.

After defining the tag library definition file above, place the tag library file in the Web app's web-inf path or any subpath, and the Java WEB specification will automatically load the file, and the tag library defined by the file will also take effect.

Using the Tag Library

It takes two points to determine the specified label in the JSP page:

1. Tag Library URI: Determine which tag library to use

2. Label name: Determine which label to use

Using the tag library is divided into the following two steps:

1. Import Tag Library: Import the tag library with the taglib compile directive, which is to associate the tag library with the specified prefix.

2. Use Tags: use custom tags in JSP pages.

The syntax format for taglib is as follows:

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

Where the URI attribute specifies the URI of the tag library, this URI can determine a tag library. The prefix property specifies the tag library prefix, which means that all tags that use the prefix will be processed by this tag library.

The syntax for using tags is as follows:

<tagprefix:tagname tagattribute= "Tagvalue" ... ><tagbody/></tagprefix:tagname>

  

If the label does not have a label body, you can use the following syntax format:

<tagprefix:tagname tagattribute= "Tagvalue" .../>

  

The syntax for using the tag above contains the setting property value, the Helloworldtag tag described above does not have any attributes, so use this tag only with <myTag:helloWorld/>. Where MyTag is the prefix specified by the taglib directive for the tag library, and HelloWorld is the label name.

Mytaglib.tld

<?xml version= "1.0" encoding= "UTF-8"? ><taglib 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/http Java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd "    version=" 2.0 ">    <tlib-version>1.0</ tlib-version>    <short-name>mytaglib</short-name>    <uri>/mytaglib</uri>    <!--define the first label        --<tag> <description> output Hello, world</description>        <!--define the label signature -        <name>helloWorld</name>        <!--define label handling classes--        <tag-class> Com.baiguiren.helloworldtag</tag-class>        <!--define the label body as empty-and        <body-content>empty</ body-content>    </tag>    </taglib>

  

hello-world-tag.jsp

<%@ page contenttype= "text/html; Charset=utf-8 "%><%@ taglib uri="/web-inf/mytaglib.tld "prefix=" MyTag "%>

  

Labels with attributes

Labels with attributes must provide a corresponding setter and getter method for each property.

Defining labels

<!--with Properties tab--<tag> <name>query</name> &LT;TAG-CLASS&GT;COM.BAIGUIREN.QUERYTAG&L T;/tag-class> <body-content>empty</body-content> <!--configuration properties: Driver-<attri bute> <name>driver</name> <required>true</required> <fragme Nt>true</fragment> </attribute> <!--configuration properties: URL--<attribute> & Lt;name>url</name> <required>true</required> <fragment>true</fragment&        Gt            </attribute> <!--Configuration properties: User--<attribute> <name>user</name>        <required>true</required> <fragment>true</fragment> </attribute> <!--Configuration Properties: Pass--<attribute> <name>pass</name> <required> True</requIred> <fragment>true</fragment> </attribute> <!--configuration properties: SQL-- <attribute> <name>sql</name> <required>true</required> < Fragment>true</fragment> </attribute> </tag>

  

Label Handling class Querytag.java

Package Com.baiguiren;import Java.io.ioexception;import java.io.writer;import java.util.date;import java.sql.*; Import javax.servlet.*;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;p ublic class QueryTag extends    simpletagsupport{//Define member variables to represent the properties of the label private String driver;    Private String URL;    Private String user;    Private String Pass;    private String SQL;    object to perform database access private Connection Connection = null;    Private Statement Statement = null;    Private ResultSet ResultSet = null;    Private ResultSetMetaData resultsetmetadata = null;    The following is the setter and getter method for each member property public void Setdriver (String driver) {this.driver = driver;    } public String Getdriver () {return this.driver;    } public void SetUrl (String url) {this.url = URL;    } public String GetUrl () {return this.url;    The public void SetUser (String user) {this.user = user;    } public String GetUser () {return this.user;    }public void SetPass (String pass) {This.pass = pass;    } public String Getpass () {return this.pass;    } public void SetSQL (String sql) {this.sql = SQL;    } public String GetSQL () {return this.sql;  }//Override the Dotag () method, which generates page content for the label public void Dotag () throws Jspexception, IOException {try {//            Registered driver Class.forName (driver);            Get database Connection connection = drivermanager.getconnection (URL, user, pass);            Create Statement Object Statement = Connection.createstatement ();            Execute Query resultSet = statement.executequery (sql);            ResultSetMetaData = Resultset.getmetadata ();            Gets the number of columns int columnCount = Resultsetmetadata.getcolumncount ();            Gets the page output stream Writer out = Getjspcontext (). Getout ();            In the page output table Out.write ("<table border= ' 1 ' width= ' >"); Traversing the result set while (Resultset.next()) {Out.write ("<br>");                    Row-by-column output query to the data for (int i = 1; I <= columnCount; i + +) {out.write ("<td>");                    Out.write (resultset.getstring (i));                Out.write ("</td>");            } out.write ("</tr>");            }} catch (ClassNotFoundException classnotfoundexception) {classnotfoundexception.printstacktrace ();        throw new Jspexception ("Custom Label error" + Classnotfoundexception.getmessage ());            } catch (SQLException SQLException) {sqlexception.printstacktrace ();        throw new Jspexception ("SQL Error" + sqlexception.getmessage ()); } finally {//close result set try {if (ResultSet! = null) resultset.close                ();                if (statement! = NULL) statement.close ();   if (connection! = null) connection.close ();         } catch (SQLException sqlException2) {sqlexception2.printstacktrace (); }        }    }}

  

Using the label query-tag.jsp

<%@ page contenttype= "text/html; Charset=utf-8 "%><%@ taglib uri="/web-inf/mytaglib.tld "prefix=" MyTag "%>

  

The output of the label is still determined by the Dotag method, which queries against the property values and outputs the query result set to the current page.

For labels with attributes, you need to add <attribute.../> child elements to the <tag.../> element, and each attribute child element defines a label attribute.

<attribute.../> child elements also typically require the following child elements to be specified:

1. Name: Sets the property name, the value of the child element is the string content

2, Required: Sets whether the property is a required property, the value of the child element is true or false

3. Fragment: Sets whether this property supports dynamic content such as JSP feet, expressions, or True or false child elements.

Label with label body

Labels with tag bodies can embed other content within the tag (including static HTML and dynamic JSP content) and are typically used to perform some logical operations.

Label configuration

<!--iteration Labels-    <tag>        <name>iterator</name>        <tag-class> com.baiguiren.iteratortag</tag-class>        <!--definition tag body does not allow JSP script--        <body-content> Scriptless</body-content>        <!--configuration Label properties: Collection--        <attribute>            <name> collection</name>            <required>true</required>            <fragment>true</fragment>        </attribute>        <!--configuration Label properties: Item--        <attribute>            <name>item</name >            <required>true</required>            <fragment>true</fragment>        </attribute >    </tag>

  

iterator-tag.jsp

<%@ page contenttype= "text/html; Charset=utf-8 "%><%@ page import=" java.util.* "%><%@ taglib uri="/web-inf/mytaglib.tld "prefix=" MyTag "% >

Since the label body of the label is not empty, specify Body-content as scriptless when configuring the label.

In fact, the JSTL tag library provides a very powerful set of tags, such as ordinary output tags, as well as the label for Branch judgment, JSTL have a very complete implementation.

Label with page fragment as property

The custom label of the JSP2 specification also allows for a "page fragment" to be directly used as a property, giving the custom label a greater flexibility.

The label with "page fragment" is not very different from ordinary label, only two simple changes.

1, the label Processing class defines a property of type Jspfragment, which represents a "page fragment"

2. When using the tag library, specify a value for the tag's attribute by <jsp:attribute .../> action instruction.

<!--labels with page fragments as properties--    <tag>        <!--define label names--        <name>fragment</name>        <!--define label handling class-        <tag-class>com.baiguiren.FragmentTag</tag-class>        <!--Specifies that the label does not support the label body-- >        <body-content>empty</body-content>        <!--define label properties: Fragment----        <attribute>            <name>jspFragment</name>            <required>true</required>            <fragment>true </fragment>        </attribute>    </tag>

  

fragment.jsp

<%@ page contenttype= "text/html; Charset=utf-8 "%><%@ taglib uri="/web-inf/mytaglib.tld "prefix=" MyTag "%>

  

Fragmenttag.java

Package Com.baiguiren;import Java.io.ioexception;import Java.io.writer;import java.util.collection;import Java.util.date;import java.sql.*;import javax.servlet.*;import Javax.servlet.jsp.*;import javax.servlet.jsp.tagext . *;p Ublic class Fragmenttag extends simpletagsupport{    private jspfragment jspfragment;    public void Setjspfragment (Jspfragment jspfragment) {        this.jspfragment = jspfragment;    }    Public Jspfragment getjspfragment () {        return this.jspfragment;    }    public void Dotag () throws Jspexception, IOException {        JspWriter out = Getjspcontext (). Getout ();        Out.println ("<div style= ' padding:10px; BORDER:1PX solid black; border-radius:20px; ' > ");        Out.println ("

  

Note: Taglib inside the configuration of attribute must and JSP inside Jsp:attribute name, for example, above are jspfragment, otherwise will lead to inexplicable error.

Tags for dynamic properties

There are two additional requirements for dynamic properties than ordinary labels.

1, Label processing class also need to implement Dynamicattributes interface

2. When you configure a label, you specify that the tag supports dynamic properties by <dynamic-attributes .../> child elements.

Configuration:

<!--define tags that accept dynamic properties-    <tag>        <name>dynaAttr</name>        <tag-class> com.baiguiren.dynamicattributestag</tag-class>        <body-content>empty</body-content>        <dynamic-attributes>true</dynamic-attributes>    </tag>

  

dynamic-attributes.jsp

<%@ page contenttype= "text/html; Charset=utf-8 "%><%@ taglib uri="/web-inf/mytaglib.tld "prefix=" MyTag "%>

  

Dynamicattributestag.japackage Com.baiguiren;

Import Java.io.ioexception;import java.io.writer;import Java.util.arraylist;import Java.util.collection;import Java.util.date;import java.sql.*;import javax.servlet.*;import Javax.servlet.jsp.*;import javax.servlet.jsp.tagext  . *;p Ublic class Dynamicattributestag extends Simpletagsupport implements dynamicattributes{//save collection for each property name private    arraylist<string> keys = new arraylist<string> ();    Save a collection of values for each property private arraylist<object> values = new arraylist<object> ();        public void Dotag () throws Jspexception, IOException {jspwriter out = Getjspcontext (). Getout ();        Here simply output each attribute out.println ("<ol>");            for (int i = 0; i < keys.size (); i++) {String key = Keys.get (i);            Object value = Values.get (i);        Out.println ("<li>" + key + "=" + Value + "</li>");    } out.println ("</ol>"); } @Override public void Setdynamicattribute (string uri, string localname, OBject value) throws Jspexception {//Add attribute name Keys.add (localname);    Add attribute value Values.add (value); }}

 

Custom labels for JSP2

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.