Custom tag Learning for Servlets and JSPs

Source: Internet
Author: User
Tags tld

This article describes the simple label processor, which is not described here because the classic custom label processor is not easy to use with a simple label processor.

Refer to: "JSP Custom Label" Video of Mu-class network;

The sixth chapter of the Servlet, JSP, and Spring MVC Beginner's Guide;

IBM's "using JSP 2 to provide simpletagsupport development of custom labels";

Novice tutorials for JSP custom label articles.

Custom Labels

  Custom labels

The custom label is to encapsulate the method into a custom label processing class, and then use the method and Jstl tag to achieve, solve the JSP JavaBean and business implementation separation problem. Custom tags provide the convenience that is not possible in JavaBean, including custom tags that allow access to objects hidden in the JSP and their properties.

The implementation of a custom label is called a label processor, whereas a simple label processor is a label processor that implements the Simpletag interface (or inherits the Simpletagsupport Class). The classic label processor is a label processor that implements the implementation of the Bodytag interface (or inheriting the Bodytagsupport class).

  Inheritance structure for custom tags

    JSP<----Tag <----iterationtag<----tagsupport<----bodytagsupport<-----bodytag

    JSP<----simpletag<-----Simplesupporttag

Simple Label Processor

A simple label processor has a simple life cycle, and the method used for tag triggering in the Simpletag interface has only one------dotag, and the method executes only once. Business logic, traversal, and page content operations are implemented here. The content of the pages in the simple label processor is reflected in the instance of the Jspfragment class.

the life cycle of a simple tag is as follows:

1) The JSP container creates an instance of it through the parameterless constructor of a simple label processor, so the simple label processor must have a parameterless constructor (usually not written by itself, with the system default).

2) The JSP container passes through the Setjspcontext method, passing in the Jspcontext object: The most important method of this object is Getout (), it can return JspWriter, can return the response to the front end through the jspwriter.

3) If the custom label is nested by another custom label, the JSP container calls the SetParent method.

4) The JSP container invokes the set method for each property defined in the tag.

5) If the content of the page needs to be processed, the JSP container also invokes the Setjspbody method of the Simpletag interface, transmitting the contents of the page using the Jspfragment package. Of course, if there is no page content, then the JSP container does not call the method.

The following is an Explanation of the Simpletag interface :

Method

Description

Dotag () method

Is the core method used to write the label processing logic.

SetParent (Jsptag) method

Passes the parent label processor object to the label processor.

GetParent () method

Gets the parent label object of the current label.

Setjspcontext (Jspcontext) method

Passes the PageContext object of the JSP page to the label processor object.

Setjspbody (Jspfragment) method

Passes the Jspfragment object representing the current label body to the label processor object. (The Invoke (Writer) method in Jspfragment is used to execute the code snippet represented by the Jspfragment object)

  

is not looking at the above a large string of text, a bit of a Meng? Okay, here's an example of implementing the Simpletagsupport class (similar to the function of implementing the Simpletag interface).

First, you need to prepare a simpletag. tld file that is used to register the custom label, which is in the Apache-tomcat file, and the general address is in E:\apache-tomcat-6.0.39\webapps\examples\ Web-inf\jsp inside, the name is jsp2-example-taglib.tld.

Use a JSP page that displays the current time as a first example:

  steps to create a custom label :

1) Create a label processing class

 PackageCom.ny.tag2;Importjava.io.IOException;ImportJava.text.SimpleDateFormat;Importjava.util.Date;Importjavax.servlet.jsp.JspException;ImportJavax.servlet.jsp.JspWriter;ImportJavax.servlet.jsp.tagext.SimpleTagSupport; Public classDisplayInfoextendssimpletagsupport{@Override Public voidDotag ()throwsjspexception, IOException {simpledateformat SimpleDateFormat=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String Datestr= Simpledateformat.format (NewDate ()); JspWriter JspWriter=Getjspcontext (). Getout ();    Jspwriter.write (DATESTR); }}

2) Create a tag library file

Create a. tld file (such as Nytag.tld) in the Web-inf directory, then open the Jsp2-example-taglib.tld file with the taglib configuration we need, and after opening the file, locate the following code snippet and copy it to Nytag.tld.

If the Tid file is under the Web-inf file, Tomcat will automatically load the tag library in the TLD file. If you are in a different location, you can actually configure it in Web. Xml.

<?XML version= "1.0" encoding= "UTF-8"?><taglibxmlns= "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">    <Description>A Tag Library exercising simpletag handlers.</Description>    <tlib-version>1.0</tlib-version>    <Short-name>Simpletaglibrary</Short-name>    <URI>/simpletaglibrary</URI></taglib>

3) Register the tag in the tag library file

<?XML version= "1.0" encoding= "UTF-8"?><taglibxmlns= "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">    <Description>A Tag Library exercising simpletag handlers.</Description>    <tlib-version>1.0</tlib-version>    <Short-name>Ny</Short-name>    <URI>/ny-tag</URI>    <Tag>        <name>Dateinfo</name>        <Tag-class>Com.ny.tag2.DisplayInfo</Tag-class>        <body-content>Empty</body-content>    </Tag></taglib>

①<short-name>: Indicates the recommended prefix (this property will appear when the tag is introduced into the JSP page).

②<uri>: Indicates the URI used when referencing this tag library (note that the URI is not a URL).

③<tag>: Indicates the information to define the label.

Wheretag can set the following properties :

Property

Description

Name

Defines the name of the property, and the property name must be unique for each label.

Tag-class

Specifies the Java class for the mapping.

Required

Specifies whether the property is mandatory or optional and is set to true if it is required.

Rtexprvalue

Declares whether the Label property is valid when the expression is run and true if it is valid.

Type

The Java class type that defines the property, which is specified by default as String.

Decription

Description information

Fragment

If the attribute is declared, the property value is treated as a jspfragment.

Bodycontent

Specify the qualification of the label body, you can have the following values (to find out more can be found in the "reference"): a) Empty: Specify that the label can only function empty label use; b) Scriptless: Specifies that the label body of the tag can be a static HTML element, an expression language, However, JSP scripts are not allowed to appear.

4) Introduction of tag libraries in the page

<% @ taglib Prefix = " NY " URI = " /ny-tag " %>

5) Use the label in the page

< Body >    < Imooc:dateinfo /> </ Body >

  

So the code in the JSP page is:

<%@ Page Language="Java"ContentType="text/html; Charset=utf-8"pageencoding="UTF-8"%><%@ taglib Prefix="IMOOC"URI="/imooc-tag2" %><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd "><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><title>Insert Title here</title></Head><Body>    <Imooc:dateinfo/></Body></HTML>

  

Does it feel pretty simple? In fact, the use of custom tags more than these oh, come on!

Custom tag Learning for Servlets and JSPs

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.