Javaweb Custom Labels

Source: Internet
Author: User
Tags return tag throwable tld

When the JSP's built-in tags and tags in the JSTL tag library don't meet the requirements, developers are required to customize the label.

Turn http://www.cnblogs.com/vmax-tam/p/4145334.html

Custom labels

Let's start by developing a custom label and then say how it works!

Development Steps for custom labels

Step One

Write a generic Java class that inherits the TagSupport class ~

Package Com.vmaxtam.dotest;import Javax.servlet.jsp.tagext.tagsupport;public Class Mytagtest extends TagSupport {    }

Step Two

Overrides the parent class's Setpagecontext method, which is used to get the PageContext object for the current JSP page.

public class Mytagtest extends TagSupport {        private pagecontext pagecontext;    @Override public    void Setpagecontext (PageContext pagecontext) {        this.pagecontext=pagecontext;    }}

Step Three

Rewrite the parent class's doStartTag method, which writes the Java operation of the tag you defined, where I define a label to use to output a large piece of information to the browser:

@Override public    int doStartTag () throws Jspexception {            try {      pagecontext.getresponse (). Getwriter (). Write ("This is a big piece of information I wrote: ABCDEFGHIJKLMNOPQRSTUVWXYZ");        } catch (IOException e) {            e.printstacktrace ();            throw new RuntimeException (e);        }        return Super.dostarttag ();    }

This completes a label handler ~ Don't worry, we need to register it when we finish writing the program.

Step Four

In your Web App directory, locate the Web-inf folder and create a new TLD type file inside.

Then register your tag in it:

<?xml version= "1.0" encoding= "iso-8859-1"? ><! DOCTYPE taglib public  "-//sun Microsystems, Inc.//dtd JSP Tag Library 1.2//en"  "http://java.sun.com/dtd/ Web-jsptaglibrary_1_2.dtd "><taglib>  <tlib-version>1.0</tlib-version><!--represents the version number of the tag library-  <jsp-version>1.2</jsp-version><!--represents the version of the JSP--  <short-name>mtt</ short-name><!--your Tag library abbreviation--  <uri>http://vmaxtam.com/mytag</uri><!--your tag library's reference URI--    <tag>      <name>mytah</name><!--The name of the label you define--       <tag-class> com.vmaxtam.dotest.mytagtest</tag-class><!--corresponding label handlers: Package name + class name---      <body-content>jsp</ body-content><!--Label Body content format-  </tag> </taglib>

If you have forgotten how to write, you can refer to the TLD file in Jstl ~

Step Five

You want to import your tag library in a JSP page that uses your defined tags! Just like importing a class package

Just write the following on the JSP page:

<% @taglib uri= "Http://vmaxtam.com/mytag" prefix= "MMT"%>

Step 6

The above 5 steps have been prepared to do the work is done ~ below we use the label it!

The browser effect is as follows:

In this way, we have completed a custom label, although we know the steps, but do not know why this is OK, so, here's how it works:

The principle of custom labels

1) When the server is open, the resource files under Web-inf are loaded, including the Web. XML and TLD files, which are loaded into memory

2) We enter http://localhost:8080/TestArea/testit.jsp in the browser to access the JSP page

3) The server reads the contents of the testit.jsp while reading the

<% @taglib uri= "Http://vmaxtam.com/mytag" prefix= "MMT"%>

This sentence, you will find in memory whether there is a URI http://vmaxtam.com/mytag TLD file, can not find the error

4) Continue to read the JSP page, read the <mmt:mytag> this tag, will be the URI to find the TLD file, in the TLD file to find Mytab is defined, yes, then get its tag-class content, Then go and find the corresponding label handler.

5) Instantiate the tag handler and invoke the method inside it using the generated object

Here the server to the label handler method also has a certain call order a) void Setpagecontext (PageContext pc)--Incoming PageContext object

B) void SetParent (Tag t)--if there is a parent tag, pass in the parent tag object, and if not, pass NULL

C) int doStartTag ()-Called when the label starts executing.

D) int Doendtag ()--called when the tag is closed

E) void release ()--release resources

If you do not rewrite the method above, the system will call the method in its parent class ~

Why this sequence is called, there is evidence, below we look at the JSP is translated into the Java source files in the interception:

Private Boolean _jspx_meth_itcast_005fshowip_005f0 (PageContext _jspx_page_context) throws Throwable {Pagecont    Ext PageContext = _jspx_page_context;    JspWriter out = _jspx_page_context.getout (); Itcast:showip 1) Instantiate Showiptag object Gz.itcast.tag.ShowIpTag _jspx_th_itcast_005fshowip_005f0 = (Gz.itcast.tag.ShowIpT    AG) _005fjspx_005ftagpool_005fitcast_005fshowip_005fnobody.get (Gz.itcast.tag.ShowIpTag.class);    2) Call Setpagecontext method _jspx_th_itcast_005fshowip_005f0.setpagecontext (_jspx_page_context);  3) Call the SetParent method _jspx_th_itcast_005fshowip_005f0.setparent (NULL);   4) Call the doStartTag method int _jspx_eval_itcast_005fshowip_005f0 = _jspx_th_itcast_005fshowip_005f0.dostarttag (); 5) Call the Doendtag method if (_jspx_th_itcast_005fshowip_005f0.doendtag () = = Javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {_005FJ      Spx_005ftagpool_005fitcast_005fshowip_005fnobody.reuse (_JSPX_TH_ITCAST_005FSHOWIP_005F0);    return true; } _005fjspx_005ftagpool_005fitcast_005fshowip_005fnobody.reuSE (_JSPX_TH_ITCAST_005FSHOWIP_005F0);  return false; }

Control the contents of the tag body and the end tag

Custom labels can control whether the text in the label body and the text after the end tag are output ~

    @Override//The method that is executed when the start tag is encountered public    int doStartTag () throws jspexception {                //return tag.skip_body;//Tag body content is not output to the browser        return tag.eval_body_include;//tag body content to browser output    }        Method to execute after @Override//encounter end tag public    int Doendtag () throws jspexception {            //return tag.eval_page;//end tag content output to Browser        return tag.skip_page;//The content after the end tag is not output to the browser            }

So how do you repeat the output of the text in the tag body? Tagsupper also provides a doaftetbody method that we just need to do:

    int i = 4;    @Override//The contents of the label body once per output are called once this method public    int Doafterbody () throws Jspexception {while        (true)        {            if (i >0)            {                i--;                Return iterationtag.eval_body_again;//to execute the contents of the note body again            }else{break                ;            }                }        Return tag.skip_body;//does not output the contents of the tag body    }

The above content is to control the content of the label body output problem, then can change the contents of the label physical?

Unfortunately, with TagSupport is not possible, but we can use its sub-class Bodytagsupport, so long write a class inherit Bodytagsupport class Bar ~

public class Mytagtest extends Bodytagsupport {private PageContext pagecontext;    @Override public void Setpagecontext (PageContext pagecontext) {this.pagecontext = PageContext; } @Override public int doStartTag () throws Jspexception {//returns bodytag.eval_body_buffered, indicating the output tag body        Allow//return tag.skip_body, indicating not output content return bodytag.eval_body_buffered;    return tag.skip_body; } @Override public int doendtag () throws Jspexception {//Gets the Bodycontent object, which wraps the contents of the tag body body                Content bodycontent = This.getbodycontent ();                Using the GetString method to get string content = Bodycontent.getstring ();                Change the contents of the string, changing the lowercase to uppercase string change = Content.touppercase ();        Output to Browser try {this.pageContext.getResponse (). Getwriter (). write (change);        } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); } returnTag.skip_page; }}

The above ~ is the creation of the custom tag principle, there are some ways to deal with the content of the label body, we find it easy?

Yes, it's not easy. The label defined in this way is called a traditional label, so this is a social problem, and it is time for someone to come out and write a set of code to solve the problem, which is called: simple tag

Simple tags why learn traditional labels

Learn the traditional label is for later maintenance to some old system!!

Simple labels simpler than traditional labels in the label processor class to write simple!!!

Development steps for simple notes

In the same way, we'll start with a simple label development step, and then say how it works.

Step One

Write the label processor class, which is a generic class that inherits the Simpletagsupport class. Then rewrite its Dotag () method:

public class Mysimpletag extends Simpletagsupport {            @Override//This method will be executed when a label is encountered public        void Dotag () throws Jspexception, IOException {            System.out.println ("executed the Dotag () method in the Simple tab ~");}        }

Step Two

Register this tag in the TLD file ~ This process is the same as the traditional label

   <tag>      <name>simpletag</name>      <tag-class>com.vmaxtam.dotest.mysimpletag</ Tag-class>      <body-content>scriptless</body-content><!--here to use this process-  </tag>

Step Three

Import tag libraries in JSP files (this process is the same as traditional labels)

Step Four

Use this label (this process is the same as the traditional label)

The above is the definition of simple label process, compared with the traditional label, he simply can not rewrite a lot of methods.

The principle of simple labeling

A) As with the traditional label, get the Tag-class string, find the tag handler class

(ii) instantiation of the tag handler class

III) Invoking methods with objects ....

Simple label calls are different than traditional labels:

Simpletag interface method Execution procedure:

1) void Setjspcontext (Jspcontext pc)-Sets the PageContext object, passing in the PageContext object. Jspcontext is the parent class of PageContext. The PageContext object is obtained through the This.getjspcontext () method in the label processor class.

2) void SetParent (Jsptag parent)-The parent tag object is passed in, and the secondary method is not called if there is no parent tag. Get parent Tag object by GetParent method

3) void Setjspbody (Jspfragment jspbody)--Incoming tag body content. The label body content is encapsulated in the Jspfragment method. The content of the label body is obtained by getjspbody method. If there is no sign, the secondary method is not called.

4) void Dotag ()--Start and end tags execute the secondary method.

Why this method is called, there is evidence:

Private Boolean _jspx_meth_itcast_005fsimpledemo_005f0 (PageContext _jspx_page_context) throws Throwable {page    Context PageContext = _jspx_page_context;    JspWriter out = _jspx_page_context.getout (); Itcast:simpledemo 1) Instantiates the Simpledemo object gz.itcast.b_simple. Simpledemo _jspx_th_itcast_005fsimpledemo_005f0 = new gz.itcast.b_simple.    Simpledemo (); Org.apache.jasper.runtime.AnnotationHelper.postConstruct (_jsp_annotationprocessor, _jspx_th_itcast_    005FSIMPLEDEMO_005F0);    2) Call the Setjspcontext method and pass in the PageContext object _jspx_th_itcast_005fsimpledemo_005f0.setjspcontext (_jspx_page_context);    3) Call the SetParent method and do not execute if there is no parent tag. 4) Call the Setjspbody method and pass in the tag body content _jspx_th_itcast_005fsimpledemo_005f0.setjspbody (new Helper (0, _jspx_page_context, _jspx_    TH_ITCAST_005FSIMPLEDEMO_005F0, null));    5) Call the Dotag method, execute the label _jspx_th_itcast_005fsimpledemo_005f0.dotag (); Org.apache.jasper.runtime.AnnotationHelper.preDestroy (_jsp_annotationprocessor, _jspx_th_itcast_005fsimpledemo_    005F0); return FAlse; }
Controls whether content is output after the label body text and the end tag

We can control it by Jspfragment objects.

Tag Body content:

To output: Execute the Jspframent.invoke () method in the Dotag () method

Do not output: do nothing!!

End tag Content:

To output: do nothing!

No output: Throws a Skippageexception exception in the Dotag () Method!

@Override public        void Dotag () throws Jspexception, IOException {            jspfragment jspbody = This.getjspbody ();            Jspbody.invoke (null);                        throw new Skippageexception ();        }

So how to loop the output of the label body content, in a simple label implementation is very simple, in the Dotag method to write

    for (int i=1;i<=5;i++) {        jspbody.invoke (null);//default Write all browser    }
Change the contents of the label body

In the Dotag method, write the following:

4.1 Create a temporary writer output stream (container)        stringwriter writer = new StringWriter ();                4.2 Copy the contents of the label body to the temporary writer stream             jspfragment jspbody = This.getjspbody ();        Jspbody.invoke (writer);                4.3 Remove the contents of the tag body from the temporary writer stream        String content = writer.tostring ();                4.4 Changing the contents of the tag body content        = Content.touppercase ();                4.5 Write the changed content to the browser        //jspbody.invoke (null); If so, the original content is output        this.getjspcontext (). Getout (). Write ( content);
Output format for label body content

In addition to the ability to set the label body content output, but also to set its output format, then what kind of output format it?

You can have the following output formats:

JSP: The tag body content that represents the output can contain JSP scripts and can execute this script. This value can only be used in traditional labels.

Scriptless: Indicates that the output of the label body content cannot contain JSP script, if included error.

Empty: Indicates no label body content. is an empty label. If it is not an empty label, an error.

Tagdependent: Indicates that the output tag body content can contain JSP scripts. But does not execute JSP script (directly as output)

Then we will set the output format of the text within the TLD file:

  <tag>        <name>tagDemo</name>        <tag-class>gz.itcast.a_tag. Tagdemo1</tag-class>           <body-content>JSP</body-content><!--here set-  </tag>

It's all about the output of the tag body content, the label can also set the property, then the custom label how to define the properties of the label?

Properties for custom Labels

This process is implemented in a simple tag, here are the steps

Step One

Declare a member variable within the Tag processor class, which is used to accept the value of the Tag property, and then generate a setter method for the member variable within the Tag processor class:

public class Mysimpletag extends Simpletagsupport {        private Integer num;            public void Setnum (Integer num) {        this.num = num;    }

Step Two

To register this attribute with the TLD file, the attribute drug is registered in the <Tag> tag of the response label

  <tag>      <name>simpletag</name>      <tag-class>com.vmaxtam.dotest.mysimpletag</ tag-class>      <body-content>scriptless</body-content>            <attribute>          <name> Num</name> <!--??? -          <required>true</required><!--????????????????-->          <rtexprvalue>true</ rtexprvalue><!--??????? EL??? -      </attribute>  </tag>

Step Three

This allows you to use the attribute ~

<body>      <mmt:simpletag num= "1001" > I am the content of the tag </mmt:simpletag> I am the content after the tag  </body>

The above content can create a custom label for the basic function ~

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